# -*- coding:utf-8 -*-
import os
import sys
import json
import socket
import shutil
import threading
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from utils.cgai_io import Copy
from utils.Project import createProjectDir, setWorkspace
from utils.HUD import createHUD, clearHUD
from utils.Playblast import createMov
from utils.Camera import set_main_camera, get_main_camera_focal, get_main_camera
from utils.CgtwPath import getCgtwAssetPath, getCgtwShotPath,get_cgtw_data,setCgtwTexturePath
from utils.Detection import detectionByPipeline,checkCGTW
from utils.Exporter import exportFBX,exportABC
from .detectionWindow import DetetionWindow

try:
    reload(sys)
    sys.setdefaultencoding('utf-8')
    import maya.cmds as cmds
    import maya.mel as mel
    from maya import OpenMayaUI as omui
    from shiboken2 import wrapInstance
except Exception as import_err:
    print('test')


def maya_main_window():
    '''
    Return the Maya main window widget as a Python object
    '''
    main_window_ptr = omui.MQtUtil.mainWindow()
    return wrapInstance(long(main_window_ptr), QWidget)


class ListModel(QListWidget):
    """
    list model ,create project and shot list
    """
    data_Signal = Signal(dict)

    def __init__(self):
        super(ListModel, self).__init__()
        # self.clicked.connect(self._show_info)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.doubleClicked.connect(self._show_info)
        self.data = {}

    def set_data(self, data):
        """
        :param data:
        :return:
        """
        if data:
            self.clear()
            self.data = data
            for k, v in data.items():
                item = QListWidgetItem()
                item.setText(k)
                item.setTextAlignment(Qt.AlignCenter)
                self.addItem(item)
            self.sortItems()

    def _show_info(self, index):
        item = self.itemFromIndex(index)
        text = item.text()  # full_name fps resolution frame description path
        result = self.data[text] if text in self.data.keys() else {'description': '', 'entity_name': text,
                                                                   'full_name': '',
                                                                   'img_path': 'path', 'frame': '100',
                                                                   'resolution': '2046x1152'}
        self.data_Signal.emit(result)
        # print(self.data[text])
        self.close()

    def filter_item(self, text):
        try:
            # item_list=[]
            for i in range(self.count()):
                item = self.item(i)
                project_name = item.text()
                if text not in project_name:
                    item.setHidden(True)
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))

    def add_asset(self, asset_name):
        item = QListWidgetItem()
        item.setText(asset_name)
        item.setTextAlignment(Qt.AlignCenter)
        self.addItem(item)

    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)


class ShotListWindow(QDialog):
    """
    镜头列表，显示所有获取到的镜头信息
    """
    shot_Signal = Signal(dict)

    def __init__(self):
        super(ShotListWindow, self).__init__()
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.setWindowTitle('Shots')
        self.main_layout = QVBoxLayout()
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton('search')
        self.search_btn.clicked.connect(self._filter_shot)
        self.search_btn.setStyleSheet(self.btn_style)
        self.add_btn = QPushButton('create')
        self.add_btn.clicked.connect(self._add_asset)
        self.add_btn.setStyleSheet(self.btn_style)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.search_layout.addWidget(self.add_btn)
        self.shot_list = ListModel()
        self.shot_list.data_Signal.connect(self._get_shot)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.shot_list)
        self.setLayout(self.main_layout)

    def set_data(self, data):
        if data:
            self.shot_list.set_data(data)

    def _filter_shot(self):
        """
        filter shot
        :return:
        """
        text = self.search_edit.text()
        if text:
            self.shot_list.filter_item(text)

    def _add_asset(self):
        text = self.search_edit.text()
        if text:
            self.shot_list.add_asset(text)

    def _text_edited(self, ha):
        if not ha:  # 当没有搜索内容时，就重置
            # self.create_items(self.data_list)
            self.shot_list.show_all()

    def _get_shot(self, data):
        self.shot_Signal.emit(data)
        self.close()


class ExistDialog(QDialog):
    """
    保存houdini工程以及版本升级
    """

    def __init__(self, file_path):
        super(ExistDialog, self).__init__()
        self.file_path = file_path
        self.setWindowTitle('版本已存在')
        self.main_layout = QHBoxLayout()
        self.new_version_label = QLabel('custom version:')
        self.new_verison_edit = QLineEdit()
        rex = QRegExp("[0-9\.]+$")
        rv = QRegExpValidator(rex, self)
        self.new_verison_edit.setValidator(rv)
        self.new_verison_edit.setText('0')
        self.OK_btn = QPushButton('OK')
        self.OK_btn.clicked.connect(self._save)
        self.cover_btn = QPushButton('Cover')
        self.cover_btn.clicked.connect(self._cover)
        self.main_layout.addWidget(self.new_version_label)
        self.main_layout.addWidget(self.new_verison_edit)
        self.main_layout.addWidget(self.OK_btn)
        self.main_layout.addWidget(self.cover_btn)
        self.setLayout(self.main_layout)

    def int2str(self, number):
        if number < 10:
            return 'v00' + str(number)
        elif number < 100:
            return 'v0' + str(number)
        else:
            return 'v' + str(number)

    def update_version(self, ori_version, new_num):
        new_file_name = ''
        file_name, ex_name = os.path.splitext(ori_version)
        slite_files = file_name.split('_')
        vers = slite_files[-1]
        slite_files.remove(vers)
        if vers.startswith('v'):
            num = vers[1:]
            new_ver = new_num
            version = self.int2str(new_ver)
            slite_files.append(version)
            new_file_name = '_'.join(slite_files) + ex_name
        else:
            new_file_name = file_name + '_v001' + ex_name
        return new_file_name

    def _save(self):
        int_new_version = int(self.new_verison_edit.text())
        # new_version=self.int2str(int_new_version)
        madir_path, file_name = os.path.split(self.file_path)
        new_file_name = self.update_version(file_name, int_new_version)
        print(new_file_name)
        new_file = os.path.join(madir_path, new_file_name)
        if os.path.exists(new_file):
            QMessageBox.information(self, '已存在', '该{}版本已存在'.format(new_file_name))
        else:
            # hou.hipFile.save(new_file)
            cmds.file(rename=new_file)
            cmds.file(save=True, typ='mayaAscii')
            self.close()

    def _cover(self):
        int_new_version = int(self.new_verison_edit.text())
        dir_path, file_name = os.path.split(self.file_path)
        new_file_name = self.update_version(file_name, int_new_version)
        new_file = os.path.join(dir_path, new_file_name)
        # hou.hipFile.save(new_file)
        cmds.file(rename=new_file)
        cmds.file(save=True, typ='mayaAscii')
        self.close()


class Name(QWidget):
    """
    重命名ma文件
    """
    name_Signal = Signal(str)

    def __init__(self):
        super(Name, self).__init__()
        self.main_layout = QVBoxLayout()
        self.name_label = QLabel('Element Name:')
        self.name_edit = QLineEdit()
        self.name_btn = QPushButton('OK')
        self.name_btn.clicked.connect(self._set_name)
        self.main_layout.addWidget(self.name_label)
        self.main_layout.addWidget(self.name_edit)
        self.main_layout.addWidget(self.name_btn)
        self.setLayout(self.main_layout)

    def _set_name(self):
        name = self.name_edit.text()
        if name:
            self.name_Signal.emit(name)
            self.close()


class DirListMode(QWidget):
    path_Signal = Signal(str)
    """
    for director list model,can show childen file
    """

    def __init__(self, show_label, current_project_dir):
        super(DirListMode, self).__init__()

        # self.pipeline = pipeline
        self.data = {}
        self.current_project_dir = current_project_dir
        self.current_dir_path = ''  # director : \\192.168.1.238\cgteamwork5\GMZ\Asset_work\Animation\GMZ_kuanggongzuhe_02 or
        # file: \\192.168.1.238\cgteamwork5\GMZ\Asset_work\Animation\GMZ_kuanggongzuhe_02\GMZ_kuanggongzuhe_02_ani2_v002.mov
        self.current_child_path = ''  # just file : \\192.168.1.238\cgteamwork5\GMZ\Asset_work\Animation\GMZ_kuanggongzuhe_02\GMZ_kuanggongzuhe_02_ani2_v002.mov

        self.img_type_list = ['.jpg', '.JPG', '.png', '.PNG', '.tif', '.TIF', '.tx', '.TX']
        self.maya_type_list = ['.ma', '.mb']
        self.abc_type_list = ['anb','ABC']
        self.fbx_type_list = ['.fbx', '.FBX']
        self.video_type_list = ['.mov', '.MOV', '.mp4', '.MP4', '.avi', '.AVI']

        self.img_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'imgs')
        self.fold_icon = QIcon(os.path.join(self.img_path, 'fold.png'))
        self.img_icon = QIcon(os.path.join(self.img_path, 'img.png'))
        self.ma_icon = QIcon(os.path.join(self.img_path, 'ma.png'))
        self.fbx_icon = QIcon(os.path.join(self.img_path, 'fbx.png'))
        self.video_icon = QIcon(os.path.join(self.img_path, 'video.png'))

        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.label_font = QFont('', 12, 65)
        self.main_layout = QVBoxLayout()
        self.pipeline_label = QLabel(show_label)
        self.pipeline_label.setFont(self.label_font)
        self.pipeline_label.setAlignment(Qt.AlignCenter)
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton('search')
        self.search_btn.setStyleSheet(self.btn_style)
        self.search_btn.clicked.connect(self._filter_shot)
        self.clear_btn = QPushButton('clear')
        self.clear_btn.setStyleSheet(self.btn_style)
        self.clear_btn.clicked.connect(self._clear_filter)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.search_layout.addWidget(self.clear_btn)
        self.dir_list = QListWidget()
        self.dir_list.clicked.connect(self._select_dirpath)
        self.file_list = QListWidget()
        self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.file_list.clicked.connect(self._select_file)
        self.file_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.file_list.customContextMenuRequested.connect(self.right_menu)

        self.main_layout.addWidget(self.pipeline_label)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.dir_list)
        self.main_layout.addWidget(self.file_list)

        self.setLayout(self.main_layout)

    def set_data(self, data):
        self.data = data

        self.show_dir_list(data)

    def show_dir_list(self, data):
        self.dir_list.clear()
        self.file_list.clear()
        dir_list = data['names']
        if dir_list:
            for d in dir_list:
                item = QListWidgetItem()
                item.setText(d)
                item.setIcon(self.fold_icon)
                self.dir_list.addItem(item)
            self.dir_list.sortItems()

    def _get_dir_name(self,file_name):
        """
        通过文件类型获取本地存储目录
        :param file_name:
        :return:
        """
        ends = os.path.splitext(file_name)[1]
        if ends in self.img_type_list:
            dir_path = os.path.join(self.current_project_dir, 'images')
        elif ends in self.maya_type_list:
            dir_path = os.path.join(self.current_project_dir, 'scenes')
        elif ends in self.fbx_type_list:
            dir_path = os.path.join(self.current_project_dir, 'fbx')
        elif ends in self.video_type_list:
            dir_path = os.path.join(self.current_project_dir, 'movies')

        return dir_path

    def _check_exist(self):
        """
        check the file is already loaded
        :return:
        """
        for r in range(self.file_list.count()):
            item = self.file_list.item(r)
            file_name = item.text()
            ends = os.path.splitext(file_name)[1]
            file_path = os.path.join(self.current_project_dir,'download',file_name)
            # if ends in self.img_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'images', file_name)
            # elif ends in self.maya_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'scenes', file_name)
            # elif ends in self.fbx_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'fbx', file_name)
            # elif ends in self.video_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'movies', file_name)
            if os.path.exists(file_path):
                item.setBackground(QColor('#359f14'))
            else:
                item.setBackground(QColor('#272727'))

    def _select_dirpath(self, index):
        self.file_list.clear()
        item = self.dir_list.itemFromIndex(index)
        file_name = item.text()
        path = os.path.join(self.data['path'], file_name)
        # with open(r'F:\Temp\logs\select_direct.txt', 'w') as w:
        #     w.write(path)
        self.current_dir_path = path
        print('self.current_dir_path:',self.current_dir_path)
        # if os.path.isdir(path):
        child_file_names = os.listdir(path)
        for c in child_file_names:
            file_path = os.path.join(path, c)
            ends = os.path.splitext(c)[1]
            if os.path.isfile(file_path) and c[0] != '.' and ends not in ['.db']:
                self.file_list.addItem(item)
                item = QListWidgetItem()
                item.setText(c)
                if ends in self.img_type_list:
                    item.setIcon(self.img_icon)
                elif ends in self.maya_type_list:
                    item.setIcon(self.ma_icon)
                elif ends in self.fbx_type_list:
                    item.setIcon(self.fbx_icon)
                elif ends in self.video_type_list:
                    item.setIcon(self.video_icon)
                self.file_list.addItem(item)

        self.file_list.sortItems()
        self._check_exist()
        self.path_Signal.emit(path)  # path : xxx/xxx/xxx director or xx/xx/xx.ma file

    def _select_file(self, index):
        item = self.file_list.itemFromIndex(index)
        file_name = item.text()
        path = os.path.join(self.current_dir_path, file_name)
        self.current_child_path = path
        self.path_Signal.emit(path)

    def right_menu(self):
        rMenu = QMenu()
        openAction = QAction(u'打开', self)
        openAction.triggered.connect(self._open)
        rMenu.addAction(openAction)

        cgtwdirAction = QAction(u'显示cgtw目录', self)
        cgtwdirAction.triggered.connect(self._show_cgtw_dir)
        rMenu.addAction(cgtwdirAction)

        downloadAction = QAction(u'下载', self)
        downloadAction.triggered.connect(self._download)
        rMenu.addAction(downloadAction)

        localdirAction = QAction(u'显示本地目录', self)
        localdirAction.triggered.connect(self._show_local_dir)
        rMenu.addAction(localdirAction)

        importAction = QAction(u'导入', self)
        importAction.triggered.connect(self._import)
        rMenu.addAction(importAction)

        rMenu.exec_(QCursor.pos())

    def _open(self):
        print("self.data:",self.data)
        try:
            s_items = self.file_list.selectedItems()
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    # file_path = os.path.join(self.data['path'], file_name)
                    file_path = os.path.join(self.current_dir_path, file_name)
                    os.startfile(file_path.replace('/','\\'))
        except Exception as _download_ERR:
            QMessageBox.information(None, u'失败', str(_download_ERR))

    def _show_cgtw_dir(self):

        try:
            os.startfile(self.current_dir_path.replace('/','\\'))
        except Exception as _show_dir_ERR:
            QMessageBox.information(None, u'失败', str(_show_dir_ERR))

    def _show_local_dir(self):

        try:
            # s_items = self.file_list.selectedItems()
            # if s_items:
            #     paths = []
            #     for s in s_items:
            #         file_name = s.text()
            #         local_dir_path = self._get_dir_name(file_name)
            #         if local_dir_path not in paths:
            #             paths.append(local_dir_path)
            #     if paths:
            #         for p in paths:
            #             os.startfile(p)
            p = os.path.join(self.current_project_dir, 'download')
            os.startfile(p.replace('/','\\'))
        except Exception as _show_local_dir_ERR:
            QMessageBox.information(None, u'失败', str(_show_local_dir_ERR))

    def file_copy(self, file_name, current_dir):
        scr_path = os.path.join(self.current_dir_path, file_name)
        # ends = os.path.splitext(file_name)[1]
        tar_path =  os.path.join(current_dir,'download',file_name)
        # if ends in self.img_type_list:
        #     img_path = os.path.join(current_dir, 'images')
        #     tar_path = os.path.join(img_path, file_name)
        #
        # elif ends in self.maya_type_list:
        #     ma_path = os.path.join(current_dir, 'scenes')
        #     tar_path = os.path.join(ma_path, file_name)
        #
        # elif ends in self.abc_type_list:
        #     abc_path = os.path.join(current_dir, 'abc')
        #     tar_path = os.path.join(abc_path, file_name)
        #
        # elif ends in self.fbx_type_list:
        #     fbx_path = os.path.join(current_dir, 'fbx')
        #     tar_path = os.path.join(fbx_path, file_name)
        #
        # elif ends in self.video_type_list:
        #     video_path = os.path.join(current_dir, 'movies')
        #     tar_path = os.path.join(video_path, file_name)

        if tar_path:
            Copy.copyfile(scr_path,tar_path)


    def _download(self):
        try:
            s_items = self.file_list.selectedItems()
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    self.file_copy(file_name, self.current_project_dir)
            QMessageBox.information(None, u'完成', '下载完成')
            self._check_exist()
        except Exception as _download_ERR:
            QMessageBox.information(None, u'失败', str(_download_ERR))

    def _import(self):
        try:
            s_items = self.file_list.selectedItems()

            current_dir = self.current_project_dir
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    ends = os.path.splitext(file_name)[1]
                    file_path =  os.path.join(current_dir, 'download', file_name)
                    if ends in self.maya_type_list:
                        # file_path = os.path.join(current_dir, 'scenes', file_name)
                        cmds.file(file_path, i=True, mergeNamespacesOnClash=True, namespace=':')
                    elif ends in self.abc_type_list:
                        # file_path = os.path.join(current_dir, 'abc', file_name)
                        import_mel = 'AbcImport  "{}"'.format(file_path.replace('\\','/'))
                        mel.eval(import_mel)
                    elif ends in self.fbx_type_list:
                        # file_path = os.path.join(current_dir, 'fbx', file_name)
                        cmds.file(file_path, i=True)

            QMessageBox.information(None, u'完成', '导入完成')
        except Exception as _import_ERR:
            QMessageBox.information(None, u'失败', str(_import_ERR))

    def filter_item(self, text):
        try:
            for i in range(self.dir_list.count()):
                item = self.dir_list.item(i)
                show_text = item.text()
                if text not in show_text:
                    item.setHidden(True)
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))

    def show_all(self):
        for i in range(self.dir_list.count()):
            item = self.dir_list.item(i)
            item.setHidden(False)

    def _clear_filter(self):
        self.search_edit.clear()
        self.show_all()

    def _filter_shot(self):
        """
        filter shot
        :return:
        """
        text = self.search_edit.text()
        if text:
            self.filter_item(text)
        else:
            self.show_all()

    def _text_edited(self, ha):
        if not ha:
            self.show_all()


class FileListMode(QWidget):
    """
    file list model , shoe cgtw files
    """
    path_Signal = Signal(str)

    def __init__(self, show_label, current_project_dir):
        super(FileListMode, self).__init__()
        # self.pipeline = pipeline
        self.data = {}  # {dir_path:xxx,file_list:[]}
        self.current_project_dir = current_project_dir

        self.label_font = QFont('', 12, 65)
        self.img_type_list = ['.jpg', '.JPG', '.png', '.PNG', '.tif', '.TIF', '.tx', '.TX']
        self.maya_type_list = ['.ma', '.mb']
        self.abc_type_list = ['.abc', '.ABC']
        self.fbx_type_list = ['.fbx', '.FBX']
        self.video_type_list = ['.mov', '.MOV', '.mp4', '.MP4', '.avi', '.AVI']
        self.img_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'imgs')
        self.fold_icon = QIcon(os.path.join(self.img_path, 'fold.png'))
        self.img_icon = QIcon(os.path.join(self.img_path, 'img.png'))
        self.ma_icon = QIcon(os.path.join(self.img_path, 'ma.png'))
        self.abc_icon = QIcon(os.path.join(self.img_path, 'abc.png'))
        self.fbx_icon = QIcon(os.path.join(self.img_path, 'fbx.png'))
        self.video_icon = QIcon(os.path.join(self.img_path, 'video.png'))
        self.main_layout = QVBoxLayout()
        self.pipeline_label = QLabel(show_label)
        self.pipeline_label.setFont(self.label_font)
        self.pipeline_label.setAlignment(Qt.AlignCenter)
        self.file_list = QListWidget()
        self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.file_list.clicked.connect(self._select_path)
        self.file_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.file_list.customContextMenuRequested.connect(self.right_menu)
        self.main_layout.addWidget(self.pipeline_label)
        self.main_layout.addWidget(self.file_list)
        self.setLayout(self.main_layout)

    def set_data(self, data):
        """
        has key:
            dir_path : the  file director path
            file_list : the file name(not path) under dir_path eg:[xxx.mov,qq.ma,...]
        :param data: {path:xxx,names:[]}
        :return:
        """
        if data:
            self.file_list.clear()
            self.data = data

            for f in data['names']:
                item = QListWidgetItem()
                item.setText(f)
                ends = os.path.splitext(f)[1]
                if ends in self.img_type_list:
                    item.setIcon(self.img_icon)
                elif ends in self.maya_type_list:
                    item.setIcon(self.ma_icon)
                elif ends in self.fbx_type_list:
                    item.setIcon(self.fbx_icon)
                elif ends in self.video_type_list:
                    item.setIcon(self.video_icon)
                self.file_list.addItem(item)
            self.file_list.sortItems()
            self._check_exist()

    def _select_path(self, index):
        # print(index)
        item = self.file_list.itemFromIndex(index)
        file_name = item.text()
        path = os.path.join(self.data['path'], file_name)
        self.path_Signal.emit(path)

    def _check_exist(self):
        """
        check the file is already loaded
        :return:
        """
        for r in range(self.file_list.count()):
            item = self.file_list.item(r)
            file_name = item.text()
            # ends = os.path.splitext(file_name)[1]
            file_path = os.path.join(self.current_project_dir,'download',file_name)
            # if ends in self.img_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'img', file_name)
            # elif ends in self.maya_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'ma', file_name)
            # elif ends in self.fbx_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'fbx', file_name)
            # elif ends in self.video_type_list:
            #     file_path = os.path.join(self.current_project_dir, 'video', file_name)
            if os.path.exists(file_path):
                item.setBackground(QColor('#359f14'))
            else:
                item.setBackground(QColor('#272727'))

    def right_menu(self):
        rMenu = QMenu()
        openAction = QAction(u'打开', self)
        openAction.triggered.connect(self._open)
        rMenu.addAction(openAction)

        cgtwdirAction = QAction(u'显示cgtw目录', self)
        cgtwdirAction.triggered.connect(self._show_cgtw_dir)
        rMenu.addAction(cgtwdirAction)

        downloadAction = QAction(u'下载', self)
        downloadAction.triggered.connect(self._download)
        rMenu.addAction(downloadAction)

        localdirAction = QAction(u'显示本地目录', self)
        localdirAction.triggered.connect(self._show_local_dir)
        rMenu.addAction(localdirAction)

        importAction = QAction(u'导入', self)
        importAction.triggered.connect(self._import)
        rMenu.addAction(importAction)

        rMenu.exec_(QCursor.pos())

    def _open(self):
        print('FileListMode data:',self.data)
        try:
            s_items = self.file_list.selectedItems()
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    file_path = os.path.join(self.data['path'], file_name)
                    os.startfile(file_path.replace('/','\\'))
        except Exception as _download_ERR:
            QMessageBox.information(None, u'失败', str(_download_ERR))

    def _show_cgtw_dir(self):

        try:
            os.startfile(self.data['path'].replace('/','\\'))
        except Exception as _show_cgtw_dir_ERR:
            QMessageBox.information(None, u'失败', str(_show_cgtw_dir_ERR))

    def _show_local_dir(self):

        try:
            # s_items = self.file_list.selectedItems()
            # if s_items:
            #     paths = []
            #     for s in s_items:
            #         file_name = s.text()
            #         dir_name = os.path.splitext(file_name)[1][1:]
            #         dir_path = os.path.join(self.current_project_dir, dir_name)
            #         if dir_path not in paths:
            #             paths.append(dir_path)
            #     if paths:
            #         for p in paths:
            #             os.startfile(p)
            p = os.path.join(self.current_project_dir, 'download')
            os.startfile(self.current_dir_path.replace('/','\\'))

        except Exception as _show_local_dir_ERR:
            QMessageBox.information(None, u'失败', str(_show_local_dir_ERR))

    def file_copy(self, file_name, current_dir):
        scr_path = os.path.join(self.data['path'], file_name)
        # ends = os.path.splitext(file_name)[1]
        tar_path = os.path.join(current_dir,'download',file_name)
        # if ends in self.img_type_list:
        #     img_path = os.path.join(current_dir, 'img')
        #     tar_path = os.path.join(img_path, file_name)
        #
        # elif ends in self.maya_type_list:
        #     ma_path = os.path.join(current_dir, 'scenes')
        #     tar_path = os.path.join(ma_path, file_name)
        #
        # elif ends in self.abc_type_list:
        #     abc_path = os.path.join(current_dir, 'abc')
        #     tar_path = os.path.join(abc_path, file_name)
        #
        # elif ends in self.fbx_type_list:
        #     fbx_path = os.path.join(current_dir, 'fbx')
        #     tar_path = os.path.join(fbx_path, file_name)
        #
        # elif ends in self.video_type_list:
        #     video_path = os.path.join(current_dir, 'video')
        #     tar_path = os.path.join(video_path, file_name)

        if tar_path:
            shutil.copy(scr_path, tar_path)

    def _download(self):
        try:
            s_items = self.file_list.selectedItems()

            current_dir = self.current_project_dir
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    self.file_copy(file_name, current_dir)
            QMessageBox.information(None, u'完成', '下载完成')
            self._check_exist()
        except Exception as _download_ERR:
            QMessageBox.information(None, u'失败', str(_download_ERR))

    def _import(self):
        try:
            s_items = self.file_list.selectedItems()
            current_dir = self.current_project_dir
            if s_items:
                for s in s_items:
                    file_name = s.text()
                    # ends = os.path.splitext(file_name)[1]

                    file_path = os.path.join(current_dir, 'download', file_name)
                    # if ends in self.maya_type_list:
                    #     file_path = os.path.join(current_dir, 'scenes', file_name)
                    # elif ends in self.abc_type_list:
                    #     file_path = os.path.join(current_dir, 'abc', file_name)
                    # elif ends in self.fbx_type_list:
                    #     file_path = os.path.join(current_dir, 'fbx', file_name)
                    if file_path:
                        cmds.file(file_path, i=True)

            QMessageBox.information(None, u'完成', '导入完成')
        except Exception as _import_ERR:
            QMessageBox.information(None, u'失败', str(_import_ERR))


class PipelineTab(QDialog):
    """
    阶段信息窗口，显示相关阶段跟踪，动画的文件信息
    """

    def __init__(self, data_list,current_project_dir):
        super(PipelineTab, self).__init__()

        self.data_list = data_list
        self.current_project_dir = current_project_dir # 当前项目根路径
        self.current_selected_path = ''
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""

        self.setWindowTitle('获取阶段资源')
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(20)
        self.pipeline_layout = QHBoxLayout()
        self.init_pipeline_widgets(data_list)

        self.btn_layout = QHBoxLayout()
        self.open_dir_btn = QPushButton('打开目录')
        self.open_dir_btn.clicked.connect(self._open_dir)
        self.open_dir_btn.setStyleSheet(self.btn_style)
        # self.load_btn=QPushButton('下载')
        # self.load_btn.clicked.connect(self._load)
        # self.load_btn.setStyleSheet(self.btn_style)
        # self.import_btn=QPushButton('导入')
        # self.import_btn.clicked.connect(self._import_file)
        # self.import_btn.setStyleSheet(self.btn_style)
        # self.btn_layout.addWidget(self.open_dir_btn)
        # self.btn_layout.addWidget(self.load_btn)
        # self.btn_layout.addWidget(self.import_btn)

        self.main_layout.addLayout(self.pipeline_layout)
        # self.main_layout.addLayout(self.btn_layout)
        self.setLayout(self.main_layout)




    def init_pipeline_widgets(self, data_list):
        """
            mm:
                 {'pipeline':'mm','mm_path':Matchmove/eps目录,'ma_list':[ma文件所在层级所有文件包括图片，mov经过shot_name过滤的],
                 'abc':abc目录}  跟踪的也放在abc目录里 # 'abc_list':[abc目录下对应镜头的的abc文件]
            mod：
                {'pipeline':'mod','mod_path':Model目录,'mod_dirs':[dirs],'tex_path':Texture目录,'tex_dirs':[Texture目录下的abc]}
            rig：
                {'pipeline':'rig','rig_path':Rig目录,'rig_dirs':[dirs]}

            env：
                {'pipeline':'env','abc_path':abc目录(以shot_name过滤过),'abc_dirs':[dirs]}

           ani：
                {'pipeline':'ani','asset_path':Asset/Animation目录,'asset_dirs':[dirs],
                'shot_path':Shot镜头对应目录,'ma_list':[Shot目录下的ma],
                'abc_path':Shot镜头对应目录下的abc目录,'abc_dirs':[对应的各版本abc目录]}

        :param data_list:
        :return:
        """
        if data_list:
            for data in data_list:
                pipeline = data['pipeline']
                # mm
                if pipeline.startswith('mm'):
                    # mm_shot_data = {}
                    # mm_shot_data['path'] = data['maya_file_path']
                    # mm_shot_data['names'] = data['ma_list']
                    # # mm_shot = FileListMode('mm shot',self.current_project_dir)
                    # mm_shot = FileListMode('mm ma',self.current_project_dir)
                    # mm_shot.path_Signal.connect(self._get_path)
                    # mm_shot.set_data(mm_shot_data)
                    mm_ma_data = {}
                    mm_ma_data['path'] = data['maya_file_path']
                    mm_ma_data['names'] = data['ma_list']
                    mm_shot = FileListMode('mm ma',self.current_project_dir)
                    mm_shot.path_Signal.connect(self._get_path)
                    mm_shot.set_data(mm_ma_data)

                    mm_abc_data = {}
                    mm_abc_data['path'] = data['abc_path']
                    mm_abc_data['names'] = data['abc_dirs']
                    # mm_abc = FileListMode('mm abc', current_project_dir)
                    mm_abc = DirListMode('mm abc',self.current_project_dir)
                    mm_abc.path_Signal.connect(self._get_path)
                    mm_abc.set_data(mm_abc_data)
                    self.pipeline_layout.addWidget(mm_shot)
                    self.pipeline_layout.addWidget(mm_abc)

                # rig
                if pipeline.startswith('rig'):  #
                    rig_asset_data = {}
                    rig_asset_data['path'] = data['rig_path']
                    rig_asset_data['names'] = data['rig_dirs']
                    rig_asset = DirListMode('rig asset',self.current_project_dir)
                    rig_asset.path_Signal.connect(self._get_path)
                    rig_asset.set_data(rig_asset_data)
                    self.pipeline_layout.addWidget(rig_asset)

                # mod
                if pipeline.startswith('mod'):  #
                    mod_data = {}
                    mod_data['path'] = data['mod_path']
                    mod_data['names'] = data['mod_dirs']
                    mod = DirListMode('mod',self.current_project_dir)
                    mod.path_Signal.connect(self._get_path)
                    mod.set_data(mod_data)

                    tex_data = {}
                    tex_data['path'] = data['tex_path']
                    tex_data['names'] = data['tex_dirs']
                    tex = DirListMode('tex',self.current_project_dir)
                    tex.path_Signal.connect(self._get_path)
                    tex.set_data(tex_data)

                    self.pipeline_layout.addWidget(mod)
                    self.pipeline_layout.addWidget(tex)

                # env
                if pipeline.startswith('env'):  #
                    env_abc_data = {}
                    env_abc_data['path'] = data['env_path']
                    env_abc_data['names'] = data['abc_dirs']
                    env_abc = DirListMode('env abc',self.current_project_dir)
                    env_abc.path_Signal.connect(self._get_path)
                    env_abc.set_data(env_abc_data)
                    self.pipeline_layout.addWidget(env_abc)

                # animation
                if pipeline.startswith('ani'):  #
                    ani_asset_data = {}
                    ani_asset_data['path'] = data['asset_path']
                    ani_asset_data['names'] = data['asset_dirs']
                    ani_asset = DirListMode('ani asset',self.current_project_dir)
                    ani_asset.path_Signal.connect(self._get_path)
                    ani_asset.set_data(ani_asset_data)

                    ani_shot_data = {}
                    ani_shot_data['path'] = data['shot_path']
                    ani_shot_data['names'] = data['ma_list']
                    ani_shot = FileListMode('ani shot',self.current_project_dir)
                    ani_shot.path_Signal.connect(self._get_path)
                    ani_shot.set_data(ani_shot_data)

                    ani_abc_data = {}
                    ani_abc_data['path'] = data['abc_path']
                    ani_abc_data['names'] = data['abc_dirs']
                    ani_abc = DirListMode('ani abc',self.current_project_dir)
                    ani_abc.path_Signal.connect(self._get_path)
                    ani_abc.set_data(ani_abc_data)

                    self.pipeline_layout.addWidget(ani_asset)
                    self.pipeline_layout.addWidget(ani_shot)
                    self.pipeline_layout.addWidget(ani_abc)

    def init_pipeline_source(self, data):
        if data:
            if data['pipeline'] == 'mm':
                matchmove_data = {}
                matchmove_data['dir_path'] = data['matchmove_path']
                matchmove_data['file_list'] = data['matchmove']
                mm_abc_data = {}
                mm_abc_data['dir_path'] = data['abc_path']
                mm_abc_data['file_list'] = data['abc']
                self.mm_list.set_data(matchmove_data)
                self.mm_abc_list.set_data(mm_abc_data)

            if data['pipeline'].startswith('ani'):
                pass
            # for k,v in data.items():
            #     if k == 'mm':
            #         self.mm_list.set_data(v)
            #         self.mm_abc_list.set_data(v)
            #     if k=='ani':
            #         self.ani_list.set_data(v)
            #     if k == 'abc':
            #         self.abc_dir_list.set_data(v)
            #     if k=='env':
            #         self.env_list.set_data(v)

    def _get_path(self, path):
        print(path)
        self.current_selected_path = path

    def _get_abc_dir_path(self, path):
        """
        select abc director
        :param path:
        :return:
        """
        print(path)
        self.current_selected_path = path
        data = {}
        if os.path.exists(path):
            file_list = os.listdir(path)  # 这里是文件夹列表
            for i in file_list:
                if i.endswith('.ma') or i.endswith('.abc') or i.endswith('.matInfo') and not i.startswith('.'):
                    data[i] = os.path.join(path, i)
        self.abc_list.set_data(data)

    def _open_dir(self):
        if self.current_selected_path:
            rp = self.current_selected_path.replace("/", "\\")
            os.startfile(os.path.dirname(rp).replace('/','\\'))

    def _load(self):
        if self.current_selected_path and os.path.isfile(self.current_selected_path):
            ordir, file_name = os.path.split(self.current_selected_path)
            ma_path = cmds.file(q=True, sn=True)
            if ma_path:
                dir_path = self.current_project_dir
                if file_name.endswith('.fbx'):
                    dir = os.path.join(dir_path, 'fbx')
                else:  # file_name.endswith('.abc'):
                    dir = os.path.join(dir_path, 'abc')
                print('_load:', dir)
                if dir:
                    new_path = os.path.join(dir, file_name)
                    print('current_selected_path:', self.current_selected_path)
                    print('new_path:', new_path)
                    try:
                        if os.path.exists(new_path):
                            if os.path.isfile(self.current_selected_path):
                                if os.path.exists(new_path):
                                    os.remove(new_path)
                                    shutil.copy(self.current_selected_path, new_path)
                            elif os.path.isdir(self.current_selected_path):
                                if os.path.exists(new_path):
                                    shutil.rmtree(new_path)
                                    shutil.copytree(self.current_selected_path, new_path)
                        else:
                            if os.path.isfile(self.current_selected_path):
                                shutil.copy(self.current_selected_path, new_path)
                            elif os.path.isdir(self.current_selected_path):
                                shutil.copytree(self.current_selected_path, new_path)
                        QMessageBox.information(None, 'Download', u'下载完成')

                    except Exception as _load_ERR:
                        print(str(_load_ERR))
                        QMessageBox.information(None, 'erro', str(_load_ERR))
            else:
                QMessageBox.information(None, 'Erro', u'请先保存工程')

    def _import_file(self):
        """
        import select file from local path
        :return:
        """
        pass
        # if self.current_selected_path:
        #     ordir, file_name = os.path.split(self.current_selected_path)
        #     if file_name.endswith('.fbx'):
        #         dir_path = os.path.join(hou.getenv('JOB'), 'fbx')
        #     else:  # file_name.endswith('.abc'):
        #         dir_path = os.path.join(hou.getenv('JOB'), 'abc')
        #
        #     if dir_path:
        #         new_path = os.path.join(dir_path, file_name)
        #         print(new_path)
        #         if new_path.endswith('fbx'):
        #             fbx = hou.hipFile.importFBX(new_path)
        #             fbx.setPosition(hou.Vector2(10.6912, 15.3134))
        #             try:
        #                 hou.item('/obj/Asset').addNode(fbx)
        #             except Exception as item_add_ERR:
        #                 print(str(item_add_ERR))
        #             QMessageBox.information(None, 'import', '导入完成')
        #         elif new_path.endswith('abc'):
        #             abc = self._create_abc(new_path)
        #             abc.setGenericFlag(hou.nodeFlag.Display, 0)
        #             abc.setPosition(hou.Vector2(4.04098, 15.4192))
        #             merge = self._create_abc_merge(abc)
        #             try:
        #                 hou.item('/obj/Asset').addNode(abc)
        #                 hou.item('/obj/Asset').addNode(merge)
        #             except Exception as item_add_ERR:
        #                 print(str(item_add_ERR))
        #             QMessageBox.information(None, 'import', '导入完成')


class MZProgresBar(QWidget):

    def __init__(self):
        super(MZProgresBar, self).__init__()
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(0)
        label_font = QFont('', 12)
        self.show_label = QLabel(u'正在上传...')
        self.progress_layout = QHBoxLayout()
        self.progress = QProgressBar()
        self.progress.setMaximumHeight(15)
        self.percen_label = QLabel('0')
        self.percen_label.setStyleSheet('color: #d9d9d9')
        self.percen_label.setFont(label_font)
        self.progress_layout.addWidget(self.progress)
        self.progress_layout.addWidget(self.percen_label)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.progress_layout)
        self.setLayout(self.main_layout)

    def set_percent(self, percent):
        self.progress.setValue(percent)
        self.percen_label.setText(str(percent))


class CopyThread(QThread):

    def __init__(self, copy_paths, parent):
        super(CopyThread, self).__init__()
        self.copy_paths = copy_paths
        self.parent = parent

    def run(self):
        for path in self.copy_paths:
            src_path, tar_path = path
            try:
                Copy.copyall(src_path,tar_path)
                self.parent.count += 1
            except Exception as copyERR:
                print('copyERR:',copyERR)

        # for path in self.copy_paths:
        #     src_path,tar_path = path
        #     # src_path = src_path.replace('/', '\\')
        #     # tar_path = tar_path.replace('/', '\\')
        #
        #     _dir = os.path.dirname(tar_path)
        #     if not os.path.exists(_dir):
        #         os.makedirs(_dir)
        #     try:
        #         if os.path.isdir(src_path):
        #             # src_path = src_path.replace('/', '\\')
        #             # tar_path = tar_path.replace('/', '\\')
        #             Copy.copydir(src_path,tar_path)
        #         else:
        #             src_path = src_path.replace('\\', '/')
        #             tar_path = tar_path.replace('\\', '/')
        #             shutil.copyfile(src_path,tar_path)
        #         self.parent.count += 1
        #     except Exception as copyERR:
        #         print('copyERR:',src_path,copyERR)


class GlobalControl(QWidget):
    """

    """

    def __init__(self, parent=None):
        super(GlobalControl, self).__init__(parent)
        self.HOST = '192.168.1.222'
        # self.HOST = '192.168.1.178'
        self.PORT = 4455  # 5566
        self.BUFFER = 20480
        self.__plugin_path = os.path.dirname(os.path.dirname(__file__))
        self.cgtwpy_path = r'C:/CgTeamWork_v6/python/python.exe'
        self.scripy_path = os.path.join(self.__plugin_path,'utils','ExternalSubmit.py').replace('\\','/')
        self.note_path = os.path.join(self.__plugin_path,'utils','ExternalNote.py').replace('\\','/')
        self.current_artists = []  # current department artists
        self.asset_data = {}  # current artist`s all assets
        # self.dir_path = ''  # current ma dir path
        self.dep_map = {'ani': 'Animation', 'env': 'Environment', 'mod': 'Model', 'rig': 'Rig'}
        self.dep_cn_map = {'mm': u'跟踪', 'ani': u'动画', 'lgt': u'灯光', 'mod': u'模型', 'rig': u'动画','env':u'场景','efx':u'特效','cfx':u'特效'}
        self.task_data = {}  # {'efx':{'cg_id':cg_id,'task_name':efx},'efx_��������':{'cg_id':cg_id,'task_name':efx_��������}}
        self.current_asset = {}
        self.current_shot_info = {}
        self.current_project_data = {} # {'database': 'proj_pltest', 'entity_name': 'PLTEST', 'full_name': '流程测试',
        # 'eps_list': 'eps01|eps02|eps04|eps03|eps05|eps07|eps08', 'fps': '25', 'resolution':
        # '1920*1080', 'path': '\\\\192.168.1.239\\cgteamwork4\\PLTEST'}
        self.current_project_config = {} # {'fps': '25', 'color': '#3E9EFF', 'resolution': '1920*1080',
        # 'path': '\\\\192.168.1.239\\cgteamwork4\\PLTEST', 'full_name': '流程测试', 'entity_name': 'PLTEST'}



        self.ma_data = {}

        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{font-size:14px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.close_btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#1C1C1C}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""

        self.submiting_style = "QLabel{color:#ffa861}"
        self.submited_style = "QLabel{color:#77c40e}"
        self.failed_style = "QLabel{color:#ff6257}"

        self.mid_font = QFont('',11,65)
        self.setWindowTitle('GlobalControl')
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(15)

        self.drive_layout = QHBoxLayout()
        self.drive_label = QLabel(u'根目录:')
        self.drive_label.setFont(self.mid_font)
        self.driver_btn = QPushButton(r'E:/')
        self.driver_btn.clicked.connect(self._drive_changed)
        self.driver_btn.setStyleSheet(self.btn_style)

        self.drive_layout.addWidget(self.drive_label)
        self.drive_layout.addWidget(self.driver_btn)
        self.project_layout = QHBoxLayout()
        self.project_label = QLabel(u'项目名称:')
        self.project_label.setFont(self.mid_font)
        self.choose_project_btn = QPushButton('- -')
        self.choose_project_btn.setStyleSheet(self.btn_style)
        self.choose_project_btn.clicked.connect(self._open_project_window)
        self.project_layout.addWidget(self.project_label)
        self.project_layout.addWidget(self.choose_project_btn)

        self.pipeline_layout = QHBoxLayout()
        self.pipeline_label = QLabel(u'阶段:')
        self.pipeline_label.setFont(self.mid_font)
        self.pipeline_comb = QComboBox()
        self.pipeline_layout.addWidget(self.pipeline_label)
        self.pipeline_layout.addWidget(self.pipeline_comb)
        self.init_pipeline_comb()
        self.pipeline_comb.currentTextChanged.connect(self._pipeline_changed)

        self.eps_layout = QHBoxLayout()
        self.eps_label = QLabel(u'集数:')
        self.eps_label.setFont(self.mid_font)
        self.eps_comb = QComboBox()
        self.eps_comb.currentTextChanged.connect(self._eps_changed)
        self.eps_layout.addWidget(self.eps_label)
        self.eps_layout.addWidget(self.eps_comb)

        self.artists_layout = QHBoxLayout()
        self.artists_label = QLabel('Artist(资产必选):')
        self.artists_label.setFont(self.mid_font)
        self.artists_label.setVisible(False)
        self.artists_comb = QComboBox()
        self.artists_comb.setVisible(False)
        self.artists_comb.currentTextChanged.connect(self._artist_changed)
        self.artists_layout.addWidget(self.artists_label)
        self.artists_layout.addWidget(self.artists_comb)

        self.shot_layout = QHBoxLayout()
        self.shot_label = QLabel(u'资产/镜头:')
        self.shot_label.setFont(self.mid_font)
        self.shot_list_btn = QPushButton('- -')
        self.shot_list_btn.clicked.connect(self._open_shot_window)
        self.shot_list_btn.setStyleSheet(self.btn_style)
        self.shot_layout.addWidget(self.shot_label)
        self.shot_layout.addWidget(self.shot_list_btn)

        self.task_name_layout = QHBoxLayout()
        self.task_name_label = QLabel(u'任务名称:')
        self.task_name_label.setFont(self.mid_font)
        self.task_name_comb = QComboBox()
        self.task_name_comb.currentTextChanged.connect(self._task_name_changed)
        self.task_name_comb.setMinimumWidth(335)
        self.task_name_layout.addWidget(self.task_name_label)
        self.task_name_layout.addWidget(self.task_name_comb)

        self.ma_layout = QHBoxLayout()
        self.ma_label = QLabel(u'ma文件:')
        self.ma_label.setFont(self.mid_font)
        self.ma_list_comb = QComboBox()
        self.ma_list_comb.setMinimumWidth(300)
        self.ma_update_btn = QPushButton('↑↓')
        self.ma_update_btn.setFixedWidth(20)
        self.ma_update_btn.setStyleSheet(self.btn_style)
        self.ma_update_btn.clicked.connect(self._update_ma_comb)
        # self.init_ma_comb()
        self.ma_layout.addWidget(self.ma_label)
        self.ma_layout.addWidget(self.ma_list_comb)
        self.ma_layout.addWidget(self.ma_update_btn)
        self.relative_layout = QHBoxLayout()
        self.relative_label = QLabel(u'相关资产:')
        self.relative_label.setFont(self.mid_font)
        self.relative_btn = QPushButton(u'打开关联资产窗口')
        # self.relative_btn.setFont(self.mid_font)
        self.relative_btn.setStyleSheet(self.btn_style)
        self.relative_btn.clicked.connect(self._open_relative_window)
        self.cgtw_shot_btn = QPushButton(u'下载原shot')
        # self.cgtw_shot_btn.setFont(self.mid_font)
        self.cgtw_shot_btn.setStyleSheet(self.btn_style)
        self.cgtw_shot_btn.clicked.connect(self._down_load_shot)
        self.relative_layout.addWidget(self.relative_label)
        self.relative_layout.addWidget(self.relative_btn)
        self.relative_layout.addWidget(self.cgtw_shot_btn)

        self.artist_layout = QHBoxLayout()
        self.artist_label = QLabel(u'艺术家:')
        self.artist_label.setFont(self.mid_font)
        self.artist_show = QLabel('xxx')
        self.artist_show.setFont(self.mid_font)
        self.artist_layout.addWidget(self.artist_label)
        self.artist_layout.addWidget(self.artist_show)

        self.version_layout = QHBoxLayout()
        self.version_layout.setAlignment(Qt.AlignLeft)
        self.version_label = QLabel(u'版本号:')
        self.version_label.setFont(self.mid_font)
        self.version_comb = QComboBox()
        self.init_version_comb()
        self.version_comb.currentTextChanged.connect(self._update_current_version)
        self.current_version_label = QLabel(u'当前工程版本为:xxx')
        self.current_version_label.setFont(self.mid_font)
        self.set_main_camera_btn = QPushButton(u'设置主相机')
        # self.set_main_camera_btn.setFont(self.mid_font)
        self.set_main_camera_btn.setMinimumHeight(25)
        self.set_main_camera_btn.setStyleSheet(self.btn_style)
        self.set_main_camera_btn.clicked.connect(self._set_main_camera)
        self.open_cgtw_dir_btn = QPushButton(u'打开cgtw提交目录')
        # self.open_cgtw_dir_btn.setFont(self.mid_font)
        self.open_cgtw_dir_btn.setMinimumHeight(25)
        self.open_cgtw_dir_btn.setStyleSheet(self.btn_style)
        self.open_cgtw_dir_btn.clicked.connect(self._open_cgtw_dir)
        self.version_layout.addWidget(self.version_label)
        self.version_layout.addWidget(self.version_comb)
        self.version_layout.addWidget(self.current_version_label)
        self.version_layout.addWidget(self.set_main_camera_btn)
        self.version_layout.addWidget(self.open_cgtw_dir_btn)
        self._update_current_version()

        self.ma_root_tip = QLabel('')
        self._update_tip()

        self.save_layout = QHBoxLayout()
        self.save_layout.setContentsMargins(0, 20, 0, 5)
        self.save_layout.setSpacing(25)
        self.open_btn = QPushButton(u'打开ma')
        self.open_btn.setStyleSheet(self.btn_style)
        self.open_btn.clicked.connect(self._open_file)
        self.save_btn = QPushButton(u'保存\创建ma')
        self.save_btn.setStyleSheet(self.btn_style)
        self.save_btn.clicked.connect(self._save_file)
        self.version_save_btn = QPushButton(u'自增版本')
        self.version_save_btn.setStyleSheet(self.btn_style)
        self.version_save_btn.clicked.connect(self._save_update)
        self.dir_btn = QPushButton(u'打开目录')
        self.dir_btn.setStyleSheet(self.btn_style)
        self.dir_btn.clicked.connect(self._open_dir)
        self.save_layout.addWidget(self.open_btn)
        self.save_layout.addWidget(self.save_btn)
        self.save_layout.addWidget(self.version_save_btn)
        self.save_layout.addWidget(self.dir_btn)

        self.set_layout = QHBoxLayout()
        self.set_layout.setSpacing(25)
        self.set_fps_btn = QPushButton(u'匹配帧速率')
        self.set_fps_btn.setStyleSheet(self.btn_style)
        self.set_fps_btn.clicked.connect(self._set_fps)
        self.set_frame_btn = QPushButton(u'匹配帧范围')
        self.set_frame_btn.setStyleSheet(self.btn_style)
        self.set_frame_btn.clicked.connect(self._set_frame)
        self.set_1000frame_btn = QPushButton(u'偏移1000帧')
        self.set_1000frame_btn.setStyleSheet(self.btn_style)
        self.set_1000frame_btn.clicked.connect(self._set_1000frame)
        self.set_resolution_btn = QPushButton(u'匹配分辨率')
        self.set_resolution_btn.setStyleSheet(self.btn_style)
        self.set_resolution_btn.clicked.connect(self._set_resolution)

        self.set_layout.addWidget(self.set_fps_btn)
        self.set_layout.addWidget(self.set_frame_btn)
        self.set_layout.addWidget(self.set_1000frame_btn)
        self.set_layout.addWidget(self.set_resolution_btn)

        self.text_layout = QVBoxLayout()
        self.text_layout.setContentsMargins(0, 10, 0, 10)
        self.switch_layout = QHBoxLayout()
        self.text_label = QLabel(u'资产/镜头信息:')

        self.text_brower = QTextBrowser()
        self.text_brower.setMaximumHeight(150)
        self.text_layout.addLayout(self.switch_layout)
        self.text_layout.addWidget(self.text_brower)

        self.mov_layout = QHBoxLayout()
        self.mov_label = QLabel('mov小样:')
        self.mov_label.setFont(self.mid_font)
        self.mov_comb = QComboBox()
        self.mov_comb.setMinimumWidth(275)
        self.mov_update_btn = QPushButton('↑↓')
        self.mov_update_btn.setFixedWidth(20)
        self.mov_update_btn.setStyleSheet(self.btn_style)
        self.mov_update_btn.clicked.connect(self._update_mov_comb)
        self.mov_plast_btn = QPushButton(u'拍屏')
        self.mov_plast_btn.setMinimumHeight(20)
        self.mov_plast_btn.setStyleSheet(self.btn_style)
        self.mov_plast_btn.clicked.connect(self._playblast)
        self.mov_layout.addWidget(self.mov_label)
        self.mov_layout.addWidget(self.mov_comb)
        self.mov_layout.addWidget(self.mov_update_btn)
        self.mov_layout.addWidget(self.mov_plast_btn)
        self.abc_layout = QHBoxLayout()
        self.abc_label = QLabel('abc :')
        self.abc_label.setFont(self.mid_font)
        self.abc_label.setHidden(True)
        self.abc_comb = QComboBox()
        self.abc_comb.setHidden(True)
        self.abc_comb.setMinimumWidth(280)
        self.abc_update_btn = QPushButton('↑↓')
        self.abc_update_btn.setFixedWidth(15)
        self.abc_update_btn.setStyleSheet(self.btn_style)
        self.abc_update_btn.setHidden(True)
        self.abc_update_btn.clicked.connect(self._update_abc_comb)
        self.abc_export_btn = QPushButton(u'导出ABC')
        self.abc_export_btn.setMinimumHeight(20)
        self.abc_export_btn.setStyleSheet(self.btn_style)
        self.abc_export_btn.setHidden(True)
        self.abc_export_btn.clicked.connect(self._export_abc)
        self.abc_layout.addWidget(self.abc_label)
        self.abc_layout.addWidget(self.abc_comb)
        self.abc_layout.addWidget(self.abc_update_btn)
        self.abc_layout.addWidget(self.abc_export_btn)

        self.fbx_layout = QHBoxLayout()
        self.fbx_label = QLabel('fbx :')
        self.fbx_label.setFont(self.mid_font)
        self.fbx_label.setHidden(True)
        self.fbx_comb = QComboBox()
        self.fbx_comb.setHidden(True)
        self.fbx_comb.setMinimumWidth(280)
        self.fbx_update_btn = QPushButton('↑↓')
        self.fbx_update_btn.setFixedWidth(15)
        self.fbx_update_btn.setStyleSheet(self.btn_style)
        self.fbx_update_btn.setHidden(True)
        self.fbx_update_btn.clicked.connect(self._update_fbx_comb)
        self.fbx_export_btn = QPushButton(u'导出FBX')
        self.fbx_export_btn.setMinimumHeight(20)
        self.fbx_export_btn.setStyleSheet(self.btn_style)
        self.fbx_export_btn.setHidden(True)
        self.fbx_export_btn.clicked.connect(self._export_fbx)
        self.fbx_layout.addWidget(self.fbx_label)
        self.fbx_layout.addWidget(self.fbx_comb)
        self.fbx_layout.addWidget(self.fbx_update_btn)
        self.fbx_layout.addWidget(self.fbx_export_btn)
        self.madir_layout = QHBoxLayout()
        self.madir_label = QLabel(u'ma目录:')
        self.madir_label.setFont(self.mid_font)
        self.madir_label.setHidden(True)
        self.madir_comb = QComboBox()
        self.madir_comb.setHidden(True)
        self.madir_comb.setMinimumWidth(353)
        self.madir_update_btn = QPushButton('↑↓')
        self.madir_update_btn.setHidden(True)
        self.madir_update_btn.setFixedWidth(20)
        self.madir_update_btn.setStyleSheet(self.btn_style)
        self.madir_update_btn.clicked.connect(self._update_madir_comb)
        self.madir_layout.addWidget(self.madir_label)
        self.madir_layout.addWidget(self.madir_comb)
        self.madir_layout.addWidget(self.madir_update_btn)

        self.img_layout = QHBoxLayout()
        self.img_label = QLabel(u'单帧图  :')
        self.img_label.setFont(self.mid_font)
        self.img_label.setHidden(True)
        self.img_comb = QComboBox()
        self.img_comb.setHidden(True)
        self.img_comb.setMinimumWidth(353)
        self.img_update_btn = QPushButton('↑↓')
        self.img_update_btn.setHidden(True)
        self.img_update_btn.setFixedWidth(20)
        self.img_update_btn.setStyleSheet(self.btn_style)
        self.img_update_btn.clicked.connect(self._update_img_comb)
        self.img_layout.addWidget(self.img_label)
        self.img_layout.addWidget(self.img_comb)
        self.img_layout.addWidget(self.img_update_btn)
        self.render_layout = QHBoxLayout()
        self.render_label = QLabel(u'渲染文件:')
        self.render_label.setFont(self.mid_font)
        self.render_label.setHidden(True)
        self.render_comb = QComboBox()
        self.render_comb.setHidden(True)
        self.render_comb.setMinimumWidth(353)
        self.render_update_btn = QPushButton('↑↓')
        self.render_update_btn.setFixedWidth(20)
        self.render_update_btn.setStyleSheet(self.btn_style)
        self.render_update_btn.setHidden(True)
        self.render_update_btn.clicked.connect(self._update_render_comb)
        self.render_layout.addWidget(self.render_label)
        self.render_layout.addWidget(self.render_comb)
        self.render_layout.addWidget(self.render_update_btn)
        self.ud_layout = QHBoxLayout()
        self.ud_label = QLabel(u'畸变文件:')
        self.ud_label.setFont(self.mid_font)
        self.ud_label.setHidden(True)
        self.ud_comb = QComboBox()
        self.ud_comb.setHidden(True)
        self.ud_comb.setMinimumWidth(353)
        self.ud_update_btn = QPushButton('↑↓')
        self.ud_update_btn.setFixedWidth(20)
        self.ud_update_btn.setStyleSheet(self.btn_style)
        self.ud_update_btn.setHidden(True)
        self.ud_update_btn.clicked.connect(self._update_ud_comb)
        self.ud_layout.addWidget(self.ud_label)
        self.ud_layout.addWidget(self.ud_comb)
        self.ud_layout.addWidget(self.ud_update_btn)
        self.note_layout = QHBoxLayout()
        self.note_label = QLabel('note:')
        self.note_label.setFont(self.mid_font)
        self.note_text = QTextEdit()
        self.note_text.textChanged.connect(self._btn_limit)
        self.note_text.setFixedHeight(50)
        self.note_layout.addWidget(self.note_label)
        self.note_layout.addWidget(self.note_text)
        self.check_layout1 = QHBoxLayout()
        self.check_layout1.setContentsMargins(0, 15, 0, 0)
        self.check_layout1.setSpacing(15)
        self.check_layout1.setAlignment(Qt.AlignCenter)
        self.check_ma = QCheckBox(u'提交ma文件(触发note)')
        self.check_ma.setFont(self.mid_font)
        self.check_ma.setCheckState(Qt.Checked)
        self.check_ma.clicked.connect(self._sub_ma)
        self.check_mov = QCheckBox(u'提交mov')
        self.check_mov.setFont(self.mid_font)
        self.check_abc = QCheckBox(u'提交abc')
        self.check_abc.setFont(self.mid_font)
        self.check_abc.setCheckState(Qt.Unchecked)
        self.check_abc.clicked.connect(self._sub_abc)
        self.check_fbx = QCheckBox(u'提交fbx')
        self.check_fbx.setFont(self.mid_font)
        self.check_fbx.setCheckState(Qt.Unchecked)
        self.check_fbx.clicked.connect(self._sub_fbx)
        self.check_layout1.addWidget(self.check_ma)
        self.check_layout1.addWidget(self.check_mov)
        self.check_layout1.addWidget(self.check_abc)
        self.check_layout1.addWidget(self.check_fbx)

        self.check_layout2 = QHBoxLayout()
        self.check_layout2.setContentsMargins(0, 0, 0, 10)
        self.check_layout2.setSpacing(15)
        self.check_layout2.setAlignment(Qt.AlignCenter)
        self.check_madir = QCheckBox(u'提交ma目录(灯光)')
        self.check_madir.setFont(self.mid_font)
        self.check_madir.clicked.connect(self._sub_madir)
        self.check_img = QCheckBox(u'提交单帧')  # 单帧暂时放在 images下面
        self.check_img.setFont(self.mid_font)
        self.check_img.clicked.connect(self._sub_img)
        self.check_render = QCheckBox(u'提交渲染文件')  # 渲染文件放在 images下面，是一个目录
        self.check_render.setFont(self.mid_font)
        self.check_render.clicked.connect(self._sub_render)
        self.check_ud = QCheckBox(u'提交畸变图')  # 畸变图放在 ud目录下面
        self.check_ud.setFont(self.mid_font)
        self.check_ud.clicked.connect(self._sub_ud)
        self.check_layout2.addWidget(self.check_madir)
        self.check_layout2.addWidget(self.check_img)
        self.check_layout2.addWidget(self.check_render)
        self.check_layout2.addWidget(self.check_ud)

        self.submit_btn = QPushButton(u'提交任务')
        self.submit_btn.setMinimumHeight(30)
        self.submit_btn.setStyleSheet(self.close_btn_style)
        self.submit_btn.setEnabled(False)
        self.submit_btn.clicked.connect(self._submit)

        self.status_layout = QHBoxLayout()
        self.status_label = QLabel(u'状态:')
        self.status = QLabel('')
        self.status_layout.addWidget(self.status_label)
        self.status_layout.addWidget(self.status)

        self.main_layout.addLayout(self.drive_layout)
        self.main_layout.addLayout(self.project_layout)
        self.main_layout.addLayout(self.pipeline_layout)
        self.main_layout.addLayout(self.eps_layout)
        self.main_layout.addLayout(self.artists_layout)
        self.main_layout.addLayout(self.shot_layout)
        self.main_layout.addLayout(self.task_name_layout)
        self.main_layout.addLayout(self.ma_layout)
        self.main_layout.addLayout(self.relative_layout)
        self.main_layout.addLayout(self.artist_layout)
        self.main_layout.addLayout(self.version_layout)
        self.main_layout.addLayout(self.save_layout)
        self.main_layout.addLayout(self.set_layout)
        self.main_layout.addLayout(self.text_layout)
        self.main_layout.addLayout(self.mov_layout)
        self.main_layout.addLayout(self.abc_layout)
        self.main_layout.addLayout(self.fbx_layout)
        self.main_layout.addLayout(self.madir_layout)
        self.main_layout.addLayout(self.img_layout)
        self.main_layout.addLayout(self.render_layout)
        self.main_layout.addLayout(self.ud_layout)
        self.main_layout.addLayout(self.note_layout)
        self.main_layout.addLayout(self.check_layout1)
        self.main_layout.addLayout(self.check_layout2)
        self.main_layout.addWidget(self.submit_btn)
        self.main_layout.addLayout(self.status_layout)
        # self.main_layout.addWidget(self.submit_widget)

        self.setLayout(self.main_layout)

        self.timer = QBasicTimer()
        self.progress = MZProgresBar()
        self.count = 0
        self.all_count = 0
        self.currentThread = None
        self.all_path_list = []  # 所有文件对

    def set_ma_data(self,ma_data):
        if ma_data:
            self.ma_data = ma_data
            self.current_artists = ma_data['current_artists']
            self.asset_data = ma_data['asset_data']
            self.task_data = ma_data['task_data']
            self.current_asset = ma_data['current_asset']
            self.current_shot_info = ma_data['current_shot_info']
            self.current_project_data = ma_data['current_project_data']
            self.current_project_config = ma_data['current_project_config']

            self.driver_btn.setText(ma_data['driver'])
            self.choose_project_btn.setText(ma_data['project'])

            pipeline_items = [ma_data['pipeline']]
            self.pipeline_comb.addItems(pipeline_items)
            self.pipeline_comb.setCurrentText(ma_data['pipeline'])

            eps_items = [ma_data['eps']]
            self.eps_comb.addItems(eps_items)
            self.eps_comb.setCurrentText(ma_data['eps'])

            self.shot_list_btn.setText(ma_data['asset_shot_name'])

            task_name_items = [ma_data['task_name']]
            self.task_name_comb.addItems(task_name_items)
            self.task_name_comb.setCurrentText(ma_data['task_name'])


            self._update_ma_comb()
            self._update_mov_comb()

    # def init_preset(self, data):
    #     self.data = data
    #     self.driver_btn.setText(data['driver'])
    #     self.choose_project_btn.setText(data['entity_name'])
    #
    #     self.eps_comb.addItem(data['eps'])
    #     pipeline_result = self.pipeline_comb.findText(data['pipeline'])
    #     if pipeline_result > 0:
    #         self.pipeline_comb.setCurrentText(data['pipeline'])
    #     else:
    #         self.pipeline_comb.addItem(data['pipeline'])
    #         self.pipeline_comb.setCurrentText(data['pipeline'])
    #     self.shot_list_btn.setText(data['asset_shot'])
    #     self.init_ma_comb()
    #     show_text = u'所属项目:   {}'.format(data['full_name']) + '\n' + u'帧速率:     {}'.format(data['fps']) + '\n' \
    #                 + u'分辨率:     {}'.format(data['resolution']) + '\n' + u'提交路径:   {}'.format(data['path']) + '\n' \
    #                 + u'总帧数:      {}'.format(data['frame']) + '\n' + u'内容描述:   {}'.format(data['description'])
    #
    #     self.text_brower.setText(show_text)
    #
    #     cmds.currentUnit(t='{}fps'.format(data['fps']))
    #     cmds.playbackOptions(animationStartTime=1)
    #     cmds.playbackOptions(animationEndTime=data['frame'])
    #     cmds.playbackOptions(minTime=1)
    #     cmds.playbackOptions(maxTime=data['frame'])
    #     cmds.currentTime(1, edit=True)

    def update_context(self):
        """

        """
        dirve_dir = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        shot = self.shot_list_btn.text()
        task_name = self.pipeline_comb.currentText()
        job = '{}/{}/{}/{}/{}'.format(dirve_dir, project, eps, shot, task_name).replace('://', ':/')
        hprefix = '_'.join([project, eps, shot, task_name])

        # hou.setContextOption('drive', dirve_dir)
        # hou.setContextOption('project', project)
        # hou.setContextOption('eps', eps)
        # hou.setContextOption('shot', shot)
        # hou.setContextOption('task_name', task_name)
        # hou.setContextOption('hprefix', hprefix)
        # hou.setContextOption('job', job)
        #
        # hou.putenv('JOB', job)

    def _get_camera_name(self):
        """
        根据选择的信息获取当前相机名称
        无论是否为相机shot或asset都以该镜头或资产名称命名相机
        :return:
        """

        asset_shot = self.shot_list_btn.text()

        return asset_shot

    def _get_camera(self):
        cameras = cmds.ls(type='camera')

    def request_from_222(self, msg):
        """
        request data from 222
        :param msg: {'ask_type':xxx,''}
        :return:
        """
        # print(msg)
        data = {}
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.95)
        try:
            sock.connect((self.HOST, self.PORT))
            sock.send(str(msg).encode())
            all_backs = b''
            while True:
                # time.sleep(0.1)
                print(u'接收中....')
                back = sock.recv(self.BUFFER)  # socket.MSG_WAITALL#,socket.MSG_WAITALL
                # # header_len=struct.unpack(back)
                # print('接受回来:', back)
                print(u'接受回来')
                if not back:
                    break
                all_backs += back


        except Exception as request_from_222_ERR:
            print('request failed')
            print(str(request_from_222_ERR))
        finally:
            data = eval(all_backs.decode('utf8'))
            # print(data)
            sock.close()

        return data


    def _drive_changed(self):
        dir = QFileDialog.getExistingDirectory(self, '选择目录')
        print(dir)
        self.driver_btn.setText(dir)
        # hou.setContextOption('drive', dir)

    def _open_project_window(self):
        """
        request 222 get project infomation
        :return:
        """
        self.project_list_window = ListModel()
        self.project_list_window.data_Signal.connect(self._get_project_info)
        msg = {'ask_type': 'project'}
        request_project_info = self.request_from_222(msg)
        # print('request_project_info:',request_project_info)
        self.project_list_window.set_data(request_project_info)
        self.project_list_window.show()

    def _get_project_info(self, data):
        self.current_project_data = data
        project_entity_name = data['entity_name']
        # print('_get_project_info:',data)

        msg = {'ask_type': 'config', 'entity_name': project_entity_name}
        self.current_project_config = self.request_from_222(msg)
        # print('current_project_config:', self.current_project_config)
        # print('current_project_data:', self.current_project_data)
        self.current_project_config = self.current_project_config if self.current_project_config else {'fps': '',
                                                                                                       'color': '',
                                                                                                       'resolution': '',
                                                                                                       'path': '',
                                                                                                       'full_name': '',
                                                                                                       'entity_name': ''}

        self.choose_project_btn.setText(project_entity_name)
        eps_list = data['eps_list'].split('|')
        self.init_eps_comb(eps_list)

    def _eps_changed(self, current_eps):
        pipeline = self.pipeline_comb.currentText()
        self.shot_list_btn.setText('- -')
        if current_eps == 'Asset':
            self.artists_label.setVisible(True)
            self.artists_comb.setVisible(True)
            msg = {'ask_type': 'account', 'cn_department': self.dep_cn_map[pipeline]}  # 这个仅给特效，写死
            artists_data = self.request_from_222(str(msg))
            self.current_artists = artists_data.get('artists', [])
            self.current_artists.insert(0, '')
            # print('current_artists:',self.current_artists)
            self.artists_comb.clear()
            self.artists_comb.addItems(self.current_artists)
        else:
            self.artists_label.setVisible(False)
            self.artists_comb.setVisible(False)

    def _artist_changed(self, artist):
        print('current artist:', artist)
        self.shot_list_btn.setText('- -')
        msg = {'ask_type': 'artist_assets', 'database': self.current_project_data['database'], 'artist': artist}
        asset_datas = self.request_from_222(str(msg))
        # print('asset_datas:',asset_datas)
        self.asset_data = asset_datas if asset_datas != 404 else {}

    def _pipeline_changed(self, pipeline):
        self.init_ma_comb()
        if pipeline == 'cfx':
            self.driver_btn.setText(r'//192.168.8.2/fx')

    def _update_ma_comb(self):
        """
        update the local ma file in ma comblist
        :return:
        """
        self.init_ma_comb()
        self._update_current_version()

    def _open_shot_window(self):
        """
        request 222, get shot info
        :return:
        """

        if self.current_project_data:
            database = self.current_project_data['database']
            eps = self.eps_comb.currentText()

            msg = {'ask_type': 'shot', 'database': database, 'eps': eps}
            print(msg)
            data = {}
            # msg = {'ask_type': 'asset', 'database': database, 'eps': eps}
            if eps != 'Asset':

                data = self.request_from_222(msg)
                # print('_open_shot_window:',data)
            else:
                for v in self.asset_data.values():
                    entity_name = v['entity_name']
                    data[entity_name] = v

            self.shot_info_window = ShotListWindow()
            self.shot_info_window.shot_Signal.connect(self._get_shot_info)
            self.shot_info_window.set_data(data)
            self.shot_info_window.show()

    def set_task_name(self, data):
        """
        set the task_name_comb items
        :param data:
        :return:
        """
        self.task_name_comb.clear()
        if data and isinstance(data, dict):
            # print('set_task_name:',data)
            # print('set_task_name:',list(data.keys()))
            self.task_data = data
            task_name_list = list(data.keys())
            self.task_name_comb.addItems(task_name_list)
            current_task_name = self.task_name_comb.currentText()
            self.artist_show.setText(self.task_data[current_task_name]['artist'])
            self.current_asset = self.task_data[current_task_name]

    def _get_shot_info(self, data):
        """
        slot back shot data
        :param data:
        :return:
        """


        self.current_shot_info = data
        shot_name = data['entity_name']
        self.shot_list_btn.setText(shot_name)

        eps = self.eps_comb.currentText()
        pipeline_show = self.pipeline_comb.currentText()
        pipeline = pipeline_show  # self.pipeline_map[pipeline_show]
        cgtw_path = self.current_project_config['path']

        task_data = {}
        if eps != 'Asset':
            msg = {'ask_type': 'task', 'database': self.current_project_data['database'], 'eps': eps,
                   'shot_name': shot_name, 'pipeline': pipeline}
            # print('msg:',msg)
            task_data = self.request_from_222(msg)  # ����þ�ͷ�����е�task_name��cgtw��task��id
            # print('task_data:',task_data)#{'efx': {'cg_id': 'proj_pltest,shot,B96FCF09-10BC-8127-6532-0AA84BFD26F3', 'artist': '杜江帆', 'task_name': 'efx'}}
        else:  # 当是资产时，传的data为：{entity_name:data,...}
            entity_name = data['entity_name']
            # task_name_list = []
            current_artist = self.artists_comb.currentText()  # 资产的当前人员，已经确定
            for v in self.asset_data.values():  # self.asset_data为{cg_id:data,...}
                if v['entity_name'] == entity_name:
                    task_name = v['task_name']
                    v['artist'] = current_artist
                    # task_name_list.append(v['task_name'])
                    task_data[task_name] = v
        print('_get_shot_info:', task_data)
        self.set_task_name(task_data)
        self._show_shot_info()

        # self.artist_show.setText(data.get('artist','xxx'))
        self.init_ma_comb()

    def _task_name_changed(self, task_name):

        if self.task_data and task_name:
            print('_task_name_changed: self.task_data:', self.task_data)
            print('task_name：', task_name)
            data = self.task_data.get(task_name, {})
            print('_task_name_changed,data:', data)
            # self.artist_show.setText(data.get('artist'))
            self.artist_show.setText(self.task_data[task_name]['artist'])

    def _open_relative_window(self):

        print('_open_relative_window start')
        try:
            data_list = []
            cgtw_path = self.current_project_config['path']  #  if self.current_project_config else self.data['path']
            project_name = self.choose_project_btn.text()
            eps = self.eps_comb.currentText()
            shot_name = self.shot_list_btn.text()
            pipeline = self.pipeline_comb.currentText()
            if pipeline.startswith('mm'):  # 当前是跟踪，则需要关联窗口数据 mod , ani
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                ani_data = get_cgtw_data(cgtw_path, eps, shot_name, 'ani')
                data_list = [mod_data, ani_data]
            elif pipeline.startswith('ani'):  # 当前是动画阶段，则需要跟踪，模型，绑定 mm mod rig
                mm_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mm')
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                rig_data = get_cgtw_data(cgtw_path, eps, shot_name, 'rig')
                data_list = [mm_data, mod_data, rig_data]
            elif pipeline.startswith('rig'):  # 当前是绑定阶段，模型，绑定  mode
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                data_list = [mod_data]
            elif pipeline.startswith('cfx'):  # 当前是绑定阶段，模型，绑定  mode
                mm_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mm')
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                rig_data = get_cgtw_data(cgtw_path, eps, shot_name, 'rig')
                data_list = [mm_data,mod_data,rig_data]
            elif pipeline.startswith('env'):  # 当前是场景阶段，需要mm,模型  mm mode
                mm_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mm')
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                data_list = [mm_data, mod_data]
            elif pipeline.startswith('lgt'):  # 当前是渲染阶段，需要mm,mod,ani,env
                mm_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mm')
                mod_data = get_cgtw_data(cgtw_path, eps, shot_name, 'mod')
                ani_data = get_cgtw_data(cgtw_path, eps, shot_name, 'ani')
                env_data = get_cgtw_data(cgtw_path, eps, shot_name, 'env')
                data_list = [mm_data, mod_data, ani_data, env_data]
            print('_open_relative_window 004')
            current_project_dir = self._getProjectDir()
            self.relative_window = PipelineTab(data_list,current_project_dir)
            print('_open_relative_window 005')
            self.relative_window.show()
        except Exception as _open_relative_window_ERR:
            # with open(r'F:\Temp\logs\_open_relative_window_ERR.txt','w') as w:
            #     w.write(str(_open_relative_window_ERR))

            print('_open_relative_window_ERR:', _open_relative_window_ERR)

    def _down_load_shot(self):
        eps = self.eps_comb.currentText()
        shot_path = os.path.join(self.current_project_config.get('project_material_path',''),'0007_Shot',eps)
        print('shot_path:',shot_path)
        # print('project_material_path:',self.current_project_config.get('project_material_path',''))
        get_mov = QFileDialog.getOpenFileName(self, u'选择文件', shot_path, 'Shot(*.mov ; *.mp4)')
        if get_mov:
            mov_path = get_mov[0]
            print(mov_path)
            mov_name = os.path.split(mov_path)[1]
            project_path = self._getProjectDir()
            local_dir = os.path.join(project_path,'shot')
            if not os.path.exists(local_dir):
                os.mkdir(local_dir)
            local_shot = os.path.join(local_dir,mov_name)
            shutil.copyfile(mov_path,local_shot)
            QMessageBox.information(None,u'提示',u'已下载shot至\n{}'.format(local_shot))
        else:
            QMessageBox.information(None, u'错误',u'下载失败')

    def init_version_comb(self):
        versions = []
        for i in range(1, 40):
            ver = 'v%03d' % i
            versions.append(ver)

        self.version_comb.addItems(versions)

    def _update_current_version(self, signal=None):
        is_version = False
        version = 'v001'
        ma_path = None
        try:
            ma_path = cmds.file(q=True, sn=True)
        except Exception as cmds_MISS:
            pass
        if ma_path:
            np = os.path.split(ma_path)[-1]
            name = os.path.splitext(np)[0]
            # np_split = name.split('_')
            # _version = np_split[-1]
            _version = name[-4:]
            if _version.startswith('v'):
                numb = version[1:]
                try:
                    inum = int(numb)
                    is_version = True
                    version = _version
                except Exception as num_ERR:
                    is_version = False

        self.current_version_label.setText(u'当前工程版本:{}'.format(version))
        current_version_comb = self.version_comb.currentText()
        if current_version_comb == version:
            self.current_version_label.setStyleSheet('QLabel{color : #77c40e}')
        else:
            self.current_version_label.setStyleSheet('QLabel{color : #ff483d}')

    def _set_main_camera(self):
        """
        对选择的相机设置名称
        :return:
        """
        asset_shot_name = self.shot_list_btn.text()
        if '-' in asset_shot_name:
            QMessageBox.information(None, u"错误", u'maya镜头命名不支持-连接')
            return
        if asset_shot_name:
            result = set_main_camera(asset_shot_name)
            if not result:
                QMessageBox.information(None, u"提示", u'请先选择一个相机')
        else:
            QMessageBox.information(None, u"错误", u'没有识别到资产或镜头名称')

    def _open_cgtw_dir(self):
        """
        打开cgtw提交目录
        :return:
        """
        eps = self.eps_comb.currentText()
        path_data = self._get_path_data()

        if eps != 'Asset':  # 镜头任务
            mov_path = path_data.get('mov_path','')
            if mov_path:
                cgtw_dir = os.path.dirname(mov_path)
                if os.path.exists(cgtw_dir):
                    os.startfile(cgtw_dir.replace('/','\\'))
                else:
                    try:
                        os.startfile(os.path.dirname(cgtw_dir).replace('/','\\'))
                    except Exception as _no_dir_ERR:
                        print('_no_dir_ERR:',_no_dir_ERR)
        else: # 资产任务
            dir_path = path_data.get('dir_path','')
            try:
                print('dir_path:',dir_path)
                os.startfile(dir_path.replace('/','\\'))
            except Exception as _no_dir_ERR:
                print('_no_dir_ERR:', _no_dir_ERR)


    def _get_main_camera(self):
        main_camera = None
        camera_name = self.shot_list_btn.text()
        if camera_name:
            cameras = cmds.ls(type='camera')
            for c in cameras:
                if camera_name in c:
                    main_camera = c
        return main_camera

    def _update_tip(self):
        try:
            not_in_root = u'Tip:当前ma文件不在所选项目下 !!! ,请保存ma'
            in_root = u'ma文件位置正确'
            ma_path = cmds.file(q=True, sn=True)
            if not ma_path:
                self.ma_root_tip.setText(not_in_root)
                self.ma_root_tip.setStyleSheet('QLabel{color : #ff8724}')
            # else:
            #     nuke_dir_from_root = os.path.dirname(ma_path)
            #     nuke_dir = self.nuke_dir_edit.text()
            #     if nuke_dir_from_root != nuke_dir:
            #         self.ma_root_tip.setText(not_in_root)
            #         self.ma_root_tip.setStyleSheet('QLabel{color : #ff8724}')
            #     else:
            #         self.ma_root_tip.setText(in_root)
            #         self.ma_root_tip.setStyleSheet('QLabel{color : #77c40e}')

        except Exception as ma_Miss:
            pass

    def init_config(self, config_path):
        config_data = {}
        if os.path.exists(config_path):
            with open(config_path, 'r') as r:  # ,encoding='utf8'
                config_data = eval(r.read())
        # print('config_data:', config_data)
        return config_data

    def init_data(self, path):
        data = {}
        if os.path.exists(path):
            with open(path, 'r', encoding='utf8') as r:  # ,encoding='utf8'
                data = eval(r.read())
        # print('data:', data)
        return data

    def init_project_comb(self, data):
        """
        init project_comb items
        :param data:
        :return:
        """
        if data:
            self.project_comb.clear()
            self.project_comb.addItems(sorted(list(data.keys())))

    def init_eps_comb(self, eps_list):
        """
        init eps items
        :return:
        """
        self.eps_comb.clear()
        s_list = sorted(eps_list)
        s_list.insert(0, 'Asset')
        s_list.insert(0, '')
        self.eps_comb.addItems(s_list)


    def init_pipeline_comb(self):
        pipeline_list = ['mm', 'mod', 'ani', 'rig', 'env','lgt','cfx']
        self.pipeline_comb.addItems(pipeline_list)

    def init_ma_comb(self):
        self.ma_list_comb.clear()
        hip_list = []
        drive = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        asset_shot_name = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()
        task_name = self.task_name_comb.currentText()
        version = self.version_comb.currentText()
        ma_dir_name = '{}_{}_{}'.format(asset_shot_name,task_name,version)
        if project != '- -' and asset_shot_name != '- -' and eps:
            dir_path = os.path.join(drive, project, eps, asset_shot_name, pipeline, 'scenes') if pipeline!='lgt' else \
                os.path.join(drive, project, eps, asset_shot_name, pipeline, 'scenes',ma_dir_name)
            if pipeline == 'cfx':
                dir_path = os.path.join(drive, project, eps, asset_shot_name, pipeline,'maya', 'scenes')
            if os.path.exists(dir_path):
                f_list = os.listdir(dir_path)
                for i in f_list:
                    if i.endswith('.ma'):
                        hip_list.append(i)
        self.ma_list_comb.addItems(hip_list)

    def _show_shot_info(self):  # , shot_info
        """
        pipeline changed  update the shot info
        :return:
        """
        # show_text = ''
        if self.current_shot_info:
            # print(shot_info)
            show_text = '项目: {}'.format(self.current_project_data.get('full_name', '')) + '\n' + 'FPS: {}'.format(
                self.current_project_data.get('fps', '')) + '\n' \
                        + '分辨率: {}'.format(self.current_project_data.get('resolution', '')) + '\n' + '项目路径: {}'.format(
                self.current_project_config.get('path', '')) + '\n' \
                        + '帧数: {}'.format(self.current_shot_info.get('frame', '') + '\n' + '制作内容: {}'.format(
                self.current_shot_info['description']))
            self.text_brower.setText(show_text)

    def _open_dir(self):
        ft = cmds.file(q=True, sn=True)
        dir_path = os.path.dirname(ft)
        os.startfile(dir_path.replace('/','\\'))

    def _open_file(self):
        """
        open existed hip
        :return:
        """
        drive = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        asset_shot = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()
        task_name = self.task_name_comb.currentText()
        ma_name = self.ma_list_comb.currentText()
        version = self.version_comb.currentText()
        ma_dir_name = '{}_{}_{}'.format(asset_shot, task_name, version)
        if project != '- -' and asset_shot != '- -' and eps and ma_name:
            # dir_path = os.path.join(drive, project, eps, asset_shot, pipeline)
            dir_path = self._getProjectDir()
            path = os.path.join(dir_path, 'scenes', ma_name) if pipeline != 'lgt' else os.path.join(dir_path, 'scenes', ma_dir_name,ma_name)
            cmds.file(path.replace('\\', '/'), open=True, force=1)

            setWorkspace(dir_path)
            self._update_current_version()
            self._update_mov_comb()

    def get_filetype(self):
        ft = cmds.file(q=True, sn=True)
        if ft.endswith('ma'):
            return 'mayaAscii', '.ma'
        else:
            return 'mayaBinary', '.mb'


    def _getProjectDir(self):
        """
        获取当选择的信息构建的工程目录地址
        :return:
        """
        dir_path = ''
        drive_path = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        asset_shot = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()

        if project != '- -' and asset_shot != '- -' and eps:
            dir_path = os.path.join(drive_path, project, eps, asset_shot, pipeline)
            if pipeline == 'cfx':
                dir_path = os.path.join(drive_path, project, eps, asset_shot, pipeline,'maya')

        return dir_path



    def _getAbcDir(self):
        """
        获取当前版本对应的abc提交目录
        :return:
        """
        submit_abc_dirpath = ''
        dir_path = self._getProjectDir()
        if dir_path:
            asset_shot = self.shot_list_btn.text()
            task_name = self.task_name_comb.currentText()
            version = self.version_comb.currentText()
            submit_abc_dirname = '{}_{}_abc_{}'.format(asset_shot, task_name, version)
            submit_abc_dirpath = os.path.join(dir_path, 'abc', submit_abc_dirname)

        return submit_abc_dirpath


    def _getFBXDir(self):
        """
        获取FBX目录
        :return:
        """
        submit_fbx_dirpath = ''
        dir_path = self._getProjectDir()
        if dir_path:
            submit_fbx_dirpath = os.path.join(dir_path, 'fbx', )

        return submit_fbx_dirpath



    def _createAbcDir(self):
        """
        创建 abc目录下的同版本目录
        :param :
        :return:
        """
        submit_abc_dirpath = self._getAbcDir()
        if submit_abc_dirpath:
            if not os.path.exists(submit_abc_dirpath):
                os.makedirs(submit_abc_dirpath)

    def _getUdDir(self):
        """
        获取当前版本对应的abc提交目录
        :return:
        """
        submit_ud_dirpath = ''
        drive_path = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        asset_shot = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()
        task_name = self.task_name_comb.currentText()
        version = self.version_comb.currentText()
        if project != '- -' and asset_shot != '- -' and eps:
            createProjectDir(drive_path, project, eps, asset_shot, pipeline)
            dir_path = os.path.join(drive_path, project, eps, asset_shot, pipeline)
            submit_ud_dirname = '{}_ud_{}'.format(asset_shot, version)
            submit_ud_dirpath = os.path.join(dir_path, 'ud', submit_ud_dirname)

        return submit_ud_dirpath


    def _createUdDir(self):
        """
        创建 ud目录下的同版本目录, 仅限制跟踪mm
        :param :
        :return:
        """
        submit_ud_dirpath = self._getUdDir()
        if submit_ud_dirpath:
            if not os.path.exists(submit_ud_dirpath):
                os.makedirs(submit_ud_dirpath)

    def _createRenderDir(self):
        """
        创建渲染文件目录 与版本保持一致
        :return:
        """
        project_dir = self._getProjectDir()
        if project_dir:
            asset_shot = self.shot_list_btn.text()
            # pipeline = self.pipeline_comb.currentText()
            task_name = self.task_name_comb.currentText()
            version = self.version_comb.currentText()
            render_dir_name = '{}_{}_{}'.format(asset_shot, task_name, version)
            render_dir = os.path.join(project_dir, 'images', render_dir_name)
            if not os.path.exists(render_dir):
                os.makedirs(render_dir)


    def _save_ma_data(self,isdir=False):
        """
        保存当前ma获取的信息
        :return:
        """
        ma_data = {}


        ma_data['current_artists'] = self.current_artists
        ma_data['asset_data'] = self.asset_data
        ma_data['task_data'] = self.task_data
        ma_data['current_asset'] = self.current_asset
        ma_data['current_shot_info'] = self.current_shot_info
        ma_data['current_project_data'] = self.current_project_data
        ma_data['current_project_config'] = self.current_project_config

        ma_data['driver'] = self.driver_btn.text()
        ma_data['project'] = self.choose_project_btn.text()
        ma_data['pipeline'] = self.pipeline_comb.currentText()
        ma_data['eps'] = self.eps_comb.currentText()
        ma_data['asset_shot_name'] = self.shot_list_btn.text()
        ma_data['task_name'] = self.task_name_comb.currentText()



        ma_path = cmds.file(q=True, sn=True)
        if ma_path:
            ma_fullname = os.path.split(ma_path)[1]
            ma_name = os.path.splitext(ma_fullname)[0]
            scence_dir = os.path.dirname(ma_path)

            ma_data_path = os.path.join(scence_dir,ma_name+'.cfg')

            with open(ma_data_path,'w') as w:
                w.write(str(ma_data))


    def _set_project_sourceimages(self):
        """
        将sourceimages相对路径设置到整个工程目录下的sourceimages目录下
        :return:
        """
        driver_path = self.driver_btn.text()
        project_name = self.choose_project_btn.text()
        sourceimages_path = os.path.join(driver_path,project_name,'sourceimages').replace('\\','/')
        print('sourceimages_path:',sourceimages_path)
        s = 'workspace -fr "sourceImages" "{}"'.format(sourceimages_path)
        mel.eval(s)


    def _save_file(self):
        """
        save current hip to the path as its shot name
        :return:
        """

        drive_path = self.driver_btn.text()
        project = self.choose_project_btn.text()
        eps = self.eps_comb.currentText()
        asset_shot = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()
        task_name = self.task_name_comb.currentText()
        version = self.version_comb.currentText()
        ma_dir_name = '{}_{}_{}'.format(asset_shot,task_name,version)
        if project != '- -' and asset_shot != '- -' and eps:
            dir_path = createProjectDir(drive_path, project, eps, asset_shot, pipeline)
            # dir_path = os.path.join(drive_path, project, eps, asset_shot,
            #                         pipeline)

            ma_name = asset_shot + '_' + task_name + '_' + version + '.ma'  # project+'_'+eps+'_'+
            ma_scene_path = os.path.join(dir_path, 'scenes') if pipeline!='lgt' else os.path.join(dir_path, 'scenes',ma_dir_name)
            if not os.path.exists(ma_scene_path):
                os.makedirs(ma_scene_path)
            ma_path = os.path.join(ma_scene_path, ma_name)  # self increat

            # if os.path.exists(ma_path):
            # new_hip_name = self.update_version(ma_name)
            # ma_path = os.path.join(dir_path, new_hip_name)

            cmds.file(rename=ma_path)
            cmds.file(save=True, typ='mayaAscii')
            self.init_ma_comb()
            self._update_tip()
            self._createAbcDir()
            self._createRenderDir()
            if pipeline == 'mm':
                self._createUdDir()
            self._update_current_version()
            self._save_ma_data()
            setWorkspace(dir_path)
            if pipeline in ['env']:
                self._set_project_sourceimages()
            QMessageBox.information(None, u'提示', u'已保存ma文件到\n{}'.format(ma_path))

    def int2str(self, number):
        if number < 10:
            return 'v00' + str(number)
        elif number < 100:
            return 'v0' + str(number)
        else:
            return 'v' + str(number)

    def update_version(self, ori_version):
        new_file_name = ''
        file_name, ex_name = os.path.splitext(ori_version)
        slite_files = file_name.split('_')
        vers = slite_files[-1]
        slite_files.remove(vers)
        if vers.startswith('v'):
            num = vers[1:]
            new_ver = int(num) + 1
            version = self.int2str(new_ver)
            slite_files.append(version)
            new_file_name = '_'.join(slite_files) + ex_name
        else:
            new_file_name = file_name + '_v001' + ex_name
        return new_file_name

    def _save_update(self):
        """
        autosave file update version
        """
        new_file = ''
        current_file_name = cmds.file(q=True, sn=True)  # hou.hipFile.name()

        if not current_file_name:
            pass
        else:
            madir_path, hip_name = os.path.split(current_file_name)
            new_hip_name = self.update_version(hip_name)
            new_file = os.path.join(madir_path, new_hip_name)

        if new_file:
            if os.path.exists(new_file):
                self.ex_window = ExistDialog(new_file)
                self.ex_window.show()
            else:
                # hou.hipFile.save(new_file)
                cmds.file(rename=new_file)
                cmds.file(save=True, typ='mayaAscii')
            self.init_ma_comb()
            self._update_current_version()

    def _set_frame(self):
        """
        set the frame of current hip
        :return:
        """
        frame = 1
        if self.current_shot_info:
            frame = self.current_shot_info['frame']

        cmds.playbackOptions(animationStartTime=1)
        cmds.playbackOptions(animationEndTime=frame)
        cmds.playbackOptions(minTime=1)
        cmds.playbackOptions(maxTime=frame)

    def _set_1000frame(self):
        """
        set the frame of current hip
        :return:
        """
        frame = 1
        if self.current_shot_info:
            frame = self.current_shot_info['frame']

        cmds.playbackOptions(animationStartTime=1001)
        cmds.playbackOptions(animationEndTime=(int(frame) + 1000))
        cmds.playbackOptions(minTime=1001)
        cmds.playbackOptions(maxTime=(int(frame) + 1000))

    def _set_fps(self):
        """
        set current fps
        :return:
        """
        fps = 24
        if self.current_project_data:
            fps = self.current_project_data['fps']

        cmds.currentUnit(t='{}fps'.format(fps))
        cmds.currentTime(1, edit=True)

    def _btn_limit(self):
        current_note = self.note_text.toPlainText()
        if current_note:
            self.submit_btn.setEnabled(True)
            self.submit_btn.setStyleSheet(self.btn_style)
        else:
            self.submit_btn.setEnabled(False)
            self.submit_btn.setStyleSheet(self.close_btn_style)

    def _sub_ma(self):
        checkstate = self.check_ma.isChecked()
        if checkstate:
            self.check_madir.setChecked(False)
            self.madir_label.setHidden(True)
            self.madir_comb.setHidden(True)
            self.madir_update_btn.setHidden(True)

    def _sub_abc(self):
        checkstate = self.check_abc.isChecked()
        if checkstate:

            self._update_abc_comb()
            self.abc_label.setHidden(False)
            self.abc_comb.setHidden(False)
            self.abc_update_btn.setHidden(False)
            self.abc_export_btn.setHidden(False)

        else:
            self.abc_label.setHidden(True)
            self.abc_comb.setHidden(True)
            self.abc_update_btn.setHidden(True)
            self.abc_export_btn.setHidden(True)



    def _sub_fbx(self):
        checkstate = self.check_fbx.isChecked()
        if checkstate:
            self._update_fbx_comb()
            self.fbx_label.setHidden(False)
            self.fbx_comb.setHidden(False)
            self.fbx_update_btn.setHidden(False)
            self.fbx_export_btn.setHidden(False)
        else:
            self.fbx_label.setHidden(True)
            self.fbx_comb.setHidden(True)
            self.fbx_update_btn.setHidden(True)
            self.fbx_export_btn.setHidden(True)

    def _sub_madir(self):
        checkstate = self.check_madir.isChecked()
        if checkstate:
            self.check_ma.setChecked(False)
            self._update_madir_comb()
            self.madir_label.setHidden(False)
            self.madir_comb.setHidden(False)
            self.madir_update_btn.setHidden(False)
        else:
            self.madir_label.setHidden(True)
            self.madir_comb.setHidden(True)
            self.madir_update_btn.setHidden(True)

    def _sub_img(self):
        checkstate = self.check_img.isChecked()
        if checkstate:
            self._update_img_comb()
            self.img_label.setHidden(False)
            self.img_comb.setHidden(False)
            self.img_update_btn.setHidden(False)
        else:
            self.img_label.setHidden(True)
            self.img_comb.setHidden(True)
            self.img_update_btn.setHidden(True)

    def _sub_render(self):
        checkstate = self.check_render.isChecked()
        if checkstate:
            self._update_render_comb()
            self.render_label.setHidden(False)
            self.render_comb.setHidden(False)
            self.render_update_btn.setHidden(False)
        else:
            self.render_label.setHidden(True)
            self.render_comb.setHidden(True)
            self.render_update_btn.setHidden(True)

    def _sub_ud(self):
        checkstate = self.check_ud.isChecked()
        if checkstate:
            self._update_ud_comb()
            self.ud_label.setHidden(False)
            self.ud_comb.setHidden(False)
            self.ud_update_btn.setHidden(False)
        else:
            self.ud_label.setHidden(True)
            self.ud_comb.setHidden(True)
            self.ud_update_btn.setHidden(True)



    def _get_cgtw_mov_path(self):
        """
        获取cgtw上mov提交绝对路径
        """
        cgtw_mov_path = ''
        pipeline = self.pipeline_comb.currentText()
        shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        eps = self.eps_comb.currentText()
        cgtw_path = self.current_project_config.get('path', '')
        mov = self.mov_list_comb.currentText()

        project = self.choose_project_btn.text()
        version = self.version_comb.currentText()
        # print("_get_cgtw_mov_path:",project, eps , shot_name , task_name,cgtw_path)
        if project and eps and shot_name and task_name:
            #getCgtwShotPath(pipeline,netpath,eps,shot_name,task_name,version)
            path_data = getCgtwShotPath(pipeline, self.current_project_config['path'], eps, shot_name, task_name,
                                        version) if eps != 'Asset' else getCgtwAssetPath(pipeline,
                                                                                         self.current_project_config[
                                                                                             'path'], shot_name,
                                                                                         task_name, version)

            if mov != path_data.get('mov_name', ''):
                QMessageBox.information(None, u"错误", '提交mov名称或版本不匹配')

        return cgtw_mov_path

    def _get_path_data(self):
        """
        获取当前资产或镜头的提交路径信息
        :return:
        """
        path_data = {}
        pipeline = self.pipeline_comb.currentText()
        shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        eps = self.eps_comb.currentText()
        project = self.choose_project_btn.text()
        version = self.version_comb.currentText()
        if project and eps and shot_name and task_name:
            path_data = getCgtwShotPath(pipeline, self.current_project_config['path'], eps, shot_name, task_name,
                                        version) if eps != 'Asset' else getCgtwAssetPath(pipeline,
                                                                                         self.current_project_config[
                                                                                             'path'], shot_name,
                                                                                         task_name, version)
        print("path_data:",path_data)
        return path_data

    def _check_cgtw_exist(self):

        CanDo = True
        path_data = self._get_path_data()

        if self.check_mov.isChecked():  # and self.check_ma.isChecked(): # 当两者都提交时
            cgtw_mov = path_data.get('mov_path', '')
            if os.path.exists(cgtw_mov):
                CanDo = False

        if self.check_ma.isChecked():
            cgtw_ma = path_data.get('ma_path', '')
            if os.path.exists(cgtw_ma):
                CanDo = False

        if self.check_abc.isChecked():
            cgtw_abc = path_data.get('abc_path', '')
            if os.path.exists(cgtw_abc):
                CanDo = False

        if self.check_fbx.isChecked():
            cgtw_fbx = path_data.get('fbx_path', '')
            if os.path.exists(cgtw_fbx):
                CanDo = False

        if self.check_madir.isChecked():
            cgtw_ma_dir = path_data.get('ma_dir_path', '')
            if os.path.exists(cgtw_ma_dir):
                CanDo = False

        if self.check_img.isChecked():
            cgtw_img = path_data.get('img_path', '')
            if os.path.exists(cgtw_img):
                CanDo = False

        if self.check_render.isChecked():
            cgtw_render = path_data.get('render_path', '')
            if os.path.exists(cgtw_render):
                CanDo = False

        if self.check_ud.isChecked():
            cgtw_ud = path_data.get('ud_path', '')
            if os.path.exists(cgtw_ud):
                CanDo = False

        return CanDo, path_data

    def _check_UI_selected(self):
        """
        检查当前勾选项
        :return:
        """

        result = True
        # version
        current_version = self.version_comb.currentText()

        #

        # mov
        if self.check_mov.isChecked():
            current_mov = self.mov_comb.currentText()
            mov_name = os.path.splitext(current_mov)[0] if current_mov else ''
            if not mov_name.endswith(current_version):
                QMessageBox.information(None, u'错误', u'当前mov版本不一致')
                return False

        if self.check_ma.isChecked():
            current_ma = cmds.file(q=True, sn=True)
            ma_name_path = os.path.splitext(current_ma)[0]
            if not ma_name_path.endswith(current_version):
                QMessageBox.information(None, u'错误', u'当前ma版本不一致')
                return False

        if self.check_abc.isChecked():
            current_abc_name = self.abc_comb.currentText()
            if current_abc_name:
                if not current_abc_name.endswith(current_version):
                    QMessageBox.information(None, u'错误', u'当前abc版本不一致')
                    return False
            else:
                QMessageBox.information(None, u'错误', u'没有查询到当前abc文件')
                return False

        if self.check_fbx.isChecked():
            current_fbx_name = self.fbx_comb.currentText()
            if current_fbx_name:
                fbx_name = os.path.splitext(current_fbx_name)[0]
                if not fbx_name.endswith(current_version):
                    QMessageBox.information(None, u'错误', u'当前fbx版本不一致')
                    return False
            else:
                QMessageBox.information(None, u'错误', u'没有查询到当前fbx文件')
                return False

        if self.check_madir.isChecked(): #
            current_madir_name = self.madir_comb.currentText()
            if current_madir_name:
                if not current_madir_name.endswith(current_version):
                    QMessageBox.information(None, u'错误', u'当前ma版本不一致')
                    return False
            else:
                QMessageBox.information(None, u'错误', u'没有查询到当前fbx文件')
                return False

        if self.check_render.isChecked():
            current_render_name = self.render_comb.currentText()
            if not current_render_name.endswith(current_version):
                QMessageBox.information(None, u'错误', u'当前渲染文件版本不一致')
                return False

        if self.check_ud.isChecked():
            current_ud_name = self.ud_comb.currentText()
            if not current_ud_name.endswith(current_version):
                QMessageBox.information(None, u'错误', u'当前渲染文件版本不一致')
                return False

        return result

    def _submit(self):
        # print(u'点了要有反应')
        iscgtw = checkCGTW()
        if not iscgtw:
            QMessageBox.information(self, u'提示', u'请先打开cgteamwork')
            return
        # 先检查当前选择对象有没有缺失或者不匹配版本
        check_result = self._check_UI_selected()
        if check_result:
            # 再检查当前提交文件是否以存在，是否覆盖
            check, path_data = self._check_cgtw_exist()
            if not check:
                result = QMessageBox.question(self, u'提示', u'当前提交文件已存在，是否覆盖', QMessageBox.Yes | QMessageBox.No,
                                              QMessageBox.No)  # 默认关闭界面选择No
                if result == QMessageBox.Yes:
                    self.__submit(path_data)
                else:
                    pass

            else:
                self.__submit(path_data)




    def _get_all_paths(self, path_data):
        """

        :param path_data: cgtw提交路径
        :return:
        """
        path_list = []
        pipeline = self.pipeline_comb.currentText()
        asset_shot_name = self.shot_list_btn.text()
        ma_path = cmds.file(q=True, sn=True)
        # project_dir = os.path.dirname(os.path.dirname(ma_path)) if ma_path else ''
        project_dir = self._getProjectDir()
        if self.check_mov.isChecked():
            mov_name = self.mov_comb.currentText()
            local_mov_path = os.path.join(project_dir, 'movies', mov_name) if mov_name else ''
            cgtw_mov_path = path_data.get('mov_path', '')
            if os.path.exists(local_mov_path) and cgtw_mov_path:
                path_list.append((local_mov_path, cgtw_mov_path))

        if self.check_ma.isChecked():
            cgtw_ma_path = path_data.get('ma_path', '')
            if os.path.exists(ma_path) and cgtw_ma_path:
                path_list.append((ma_path, cgtw_ma_path))
            if pipeline in ['mod','cfx']:  # 当是模型阶段时，复制贴图
                tex_path = path_data.get('tex_path',{})
                # print('tex_path:',tex_path)
                if tex_path:
                    for imgs_list in tex_path.values():
                        for i in imgs_list:
                            path_list.append((i['local_tex_path'],i['cgtw_tex_path']))
                            path_list.append((i['local_tx_path'],i['cgtw_tx_path']))
                setCgtwTexturePath(self.current_project_config['path'],asset_shot_name) # 模型的话重置贴图路径并保存ma
                cmds.file(save=True, typ='mayaAscii')

        if self.check_abc.isChecked():
            abc_name = self.abc_comb.currentText()
            local_abc_path = os.path.join(project_dir, 'abc', abc_name) if abc_name else ''
            cgtw_abc_path = path_data.get('abc_path', '')
            if os.path.exists(local_abc_path) and cgtw_abc_path:
                path_list.append((local_abc_path, cgtw_abc_path))

        if self.check_fbx.isChecked():
            fbx_name = self.fbx_comb.currentText()
            local_fbx_path = os.path.join(project_dir, 'fbx', fbx_name) if fbx_name else ''
            cgtw_fbx_path = path_data.get('fbx_path', '')
            if os.path.exists(local_fbx_path) and cgtw_fbx_path:
                path_list.append((local_fbx_path, cgtw_fbx_path))

        if self.check_madir.isChecked():
            madir_name = self.madir_comb.currentText()
            local_madir_path = os.path.join(project_dir, 'scenes', madir_name) if madir_name else ''
            cgtw_madir_path = path_data.get('madir_path', '')
            if os.path.exists(local_madir_path) and cgtw_madir_path:
                path_list.append((local_madir_path, cgtw_madir_path))


        if self.check_img.isChecked():
            img_name = self.img_comb.currentText()
            local_img_path = os.path.join(project_dir, 'sourceimages', img_name) if img_name else ''
            cgtw_img_path = path_data.get('img_path', '')
            if os.path.exists(local_img_path) and cgtw_img_path:
                path_list.append((local_img_path, cgtw_img_path))

        if self.check_render.isChecked():
            render_name = self.render_comb.currentText()
            local_render_path = os.path.join(project_dir, 'sourceimages', render_name) if render_name else ''
            cgtw_render_path = path_data.get('render_path', '')
            if os.path.exists(local_render_path) and cgtw_render_path:
                path_list.append((local_render_path, cgtw_render_path))

        if self.check_ud.isChecked():
            ud_name = self.ud_comb.currentText()
            local_ud_path = os.path.join(project_dir, 'ud', ud_name) if ud_name else ''
            cgtw_ud_path = path_data.get('ud_path', '')
            if os.path.exists(local_ud_path) and cgtw_ud_path:
                path_list.append((local_ud_path, cgtw_ud_path))

        return path_list


    def _before_submit(self):
        """
        在提交之前触发
        """
        try:
            mel.eval('addOneTabToGlobalsWindow("arnold", "Arnold Renderer", "createArnoldRendererGlobalsTab")')
            cmds.setAttr('defaultArnoldRenderOptions.autotx',0)

        except Exception as _before_submit_ERR:
            pass
        finally:
            cmds.file(save=True, typ='mayaAscii')


    def __submit(self, path_data):
        print('__submit start')
        self._before_submit()

        if self.currentThread:
            self.currentThread.quit()
            self.currentThread.wait()
        eps = self.eps_comb.currentText()
        pipeline = self.pipeline_comb.currentText()
        asset_shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        checks = detectionByPipeline(pipeline, eps, asset_shot_name,task_name)
        print('__submit result:',checks)
        self.detetionWindow = DetetionWindow(pipeline,eps,task_name,checks)
        self.detetionWindow.move(1200, 0)
        self.detetionWindow.show()

        result = True
        for i in checks.values():
            if i['result'] not in ['OK','TIP']:
                result = False
        if result:
            print(u'可以提交')
            # print(path_data)
            path_list = self._get_all_paths(path_data)
            # print('path_list:',path_list)
            self.all_path_list = path_list
            self.all_count = len(path_list)
            self.progress.show()
            c = int(len(path_list)/1000)
            it = c*800 if c > 1 else 1000
            # self.timer.start(it, self)
            self.timer.start(1000, self)
            self.currentThread = CopyThread(path_list, self)
            self.currentThread.start()
        # else:
        #     QMessageBox.information(self, u"错误", '\n'.join(result['info']))

    def _set_resolution(self):
        if self.current_project_data:
            resolution = self.current_project_data.get('resolution', '')

        if resolution:
            swidth, sheight = resolution.split('*')
            cmds.setAttr('defaultResolution.width', int(swidth))
            cmds.setAttr('defaultResolution.height', int(sheight))




    def _update_mov_comb(self):
        """
        刷新mov列表
        :return:
        """
        self.mov_comb.clear()
        project_dir = self._getProjectDir()
        if project_dir:
            movies_path = os.path.join(project_dir, 'movies')
            if os.path.exists(movies_path):
                files = os.listdir(movies_path)
                mov_list = [i for i in files if i.endswith('mov')]
                self.mov_comb.addItems(mov_list)
            # else:
            #     QMessageBox.information(None,u'错误',u'当前工程movies目录不存在')

    def _playblast(self):
        asset_shot_name = self.shot_list_btn.text()
        pipeline = self.pipeline_comb.currentText()
        task_name = self.task_name_comb.currentText()
        version = self.version_comb.currentText()
        if asset_shot_name != '- -' and task_name:

            # 拍屏前先添加hud
            main_camera_shape = get_main_camera(asset_shot_name)
            if not main_camera_shape:
                QMessageBox.information(None, '错误', '请先设置主相机')
                return
            show_name = '{}_{}_{}'.format(asset_shot_name, task_name, version)
            createHUD(show_name, main_camera_shape)

            # 然后生成mov
            dir_path = self._getProjectDir()
            if dir_path:
                movies_path = os.path.join(dir_path, 'movies')
                resolution = self.current_project_config.get('resolution')
                if resolution:
                    width, height = resolution.split('*')
                    if os.path.exists(movies_path):
                        file_name = os.path.join(movies_path, show_name + '.mov')
                        createMov(file_name, int(width), int(height))
                        self._update_mov_comb()
                    else:
                        QMessageBox.information(None, u'错误', u'未查询到本地工程movies目录')
                else:
                    result = QMessageBox.question(self, '提示', '未检测到项目分辨率是否以默认2048x1152进行拍屏', QMessageBox.Yes | QMessageBox.No,
                                                  QMessageBox.No)  # 默认关闭界面选择No
                    if result == QMessageBox.Yes:
                        if os.path.exists(movies_path):
                            file_name = os.path.join(movies_path, show_name + '.mov')
                            createMov(file_name, 2048, 1152)
                            self._update_mov_comb()
                    else:
                        print('No')

            else:
                QMessageBox.information(None, u'提示', u'请先保存ma')

            # 最后清除hud
            clearHUD()

    def _update_abc_comb(self):
        """
        更新abc显示
        :return:
        """
        try:
            self.abc_comb.clear()
            project_path = self._getProjectDir()
            abc_dir_path = os.path.join(project_path, 'abc')
            if os.path.exists(abc_dir_path):
                abc_dirs = os.listdir(abc_dir_path)
                self.abc_comb.addItems(abc_dirs)
        except Exception as _update_abc_comb_ERR:
            print('test')

    def _export_abc(self):
        """
        导出abc
        :return:
        """

        project_path = self._getProjectDir()
        if project_path:
            abc_dir_path = os.path.join(project_path, 'abc').replace('\\', '/')
            ma_path = cmds.file(q=True, sn=True)
            ma_fullname = os.path.split(ma_path)[1]
            ma_name = os.path.splitext(ma_fullname)[0]
            asset_shot_name = self.shot_list_btn.text()
            pipeline = self.pipeline_comb.currentText()
            taskname = self.task_name_comb.currentText()
            version = self.version_comb.currentText()
            abc_folder_name = '{}_{}_abc_{}'.format(asset_shot_name,taskname,version)
            abc_folder_path = os.path.join(abc_dir_path, abc_folder_name).replace('\\', '/')
            # print('abc_folder_path:',abc_folder_path)
            if os.path.exists(abc_folder_path):
                abc_file_name = '{}_{}_{}.abc'.format(asset_shot_name, taskname, version)
                abc_file_path = os.path.join(abc_folder_path,abc_file_name).replace('\\', '/')
                exportABC(abc_file_path)
                # self._update_abc_comb()
            else:
                QMessageBox.information(None,u'错误',u'没有abc对应版本目录')
        else:
            QMessageBox.information(None, u'错误', u'没有ma文件')


    def _update_fbx_comb(self):
        """
        更新FBX显示
        :return:
        """
        try:
            self.fbx_comb.clear()
            project_path = self._getProjectDir()
            fbx_dir_path = os.path.join(project_path, 'fbx')
            if os.path.exists(fbx_dir_path):
                fbxs = [i for i in os.listdir(fbx_dir_path) if i.endswith('fbx')]
                self.fbx_comb.addItems(fbxs)
        except Exception as _update_fbx_comb_ERR:
            print('test')

    def _export_fbx(self):
        """
        导出fbx
        :return:
        """

        project_path = self._getProjectDir()
        if project_path:
            ma_path = cmds.file(q=True, sn=True)
            fbx_dir_path = os.path.join(project_path, 'fbx').replace('\\', '/')
            ma_fullname = os.path.split(ma_path)[1]
            ma_name = os.path.splitext(ma_fullname)[0]
            fbx_name = ma_name+'.fbx'
            if os.path.exists(fbx_dir_path):
                fbx_path = os.path.join(fbx_dir_path,fbx_name).replace('\\','/')
                exportFBX(fbx_path)
                self._update_fbx_comb()
            else:
                QMessageBox.information(None,u'错误',u'没有fbx目录')
        else:
            QMessageBox.information(None, u'错误', u'没有ma文件')

    def _update_madir_comb(self):
        try:
            self.madir_comb.clear()
            project_dir = self._getProjectDir()
            scene_dir = os.path.join(project_dir,'scenes')
            if os.path.exists(scene_dir):
                madir_paths = [i for i in os.listdir(scene_dir) if os.path.isdir(os.path.join(scene_dir,i))]
                self.madir_comb.addItems(madir_paths)
        except Exception as _update_madir_comb_ERR:
            print('test')


    def _update_img_comb(self):
        try:
            self.img_comb.clear()
            project_path = self._getProjectDir()
            img_dir_path = os.path.join(project_path, 'sourceimages')
            if os.path.exists(img_dir_path):
                img_paths = [i for i in os.listdir(img_dir_path) if '.' in i and not i.startswith('.')]
                self.img_comb.addItems(img_paths)
        except Exception as _update_img_comb_ERR:
            print('test')

    def _update_render_comb(self):
        try:
            self.render_comb.clear()
            project_path = self._getProjectDir()
            img_dir_path = os.path.join(project_path, 'images')
            if os.path.exists(img_dir_path):
                img_paths = [i for i in os.listdir(img_dir_path) if '.' not in i]
                self.render_comb.addItems(img_paths)
        except Exception as _update_render_comb_ERR:
            print('test')

    def _update_ud_comb(self):
        try:
            self.ud_comb.clear()
            project_path = self._getProjectDir()
            ud_dir_path = os.path.join(project_path, 'ud')
            if os.path.exists(ud_dir_path):
                ud_paths = [i for i in os.listdir(ud_dir_path) if '.' not in i]
                self.ud_comb.addItems(ud_paths)
        except Exception as _update_ud_comb_ERR:
            print('test')


    def cmd_cgtw_submit(self,database,module,task_id,mov,note):# 6.1
        """
        :param database:
        :param module:
        :param task_id:
        :param mov: mov名称
        :param note:
        :return:
        """
        cmd = '''"{}" "{}" "{}" "{}" "{}" "{}" "{}"'''.format(self.cgtwpy_path,self.scripy_path,database,module,task_id,mov,note)#,movpath
        print('cmd:',cmd)
        import subprocess
        subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        print('submit over')


    def cmd_cgtw_note(self,database,module,task_id,note):#,movpath
        """
        :param database:
        :param module:
        :param shot:
        :param task_id:
        :param movpath:
        :return:
        """

        cmd = [self.cgtwpy_path,self.note_path,database,module,task_id,json.dumps(note)]
        print('cmd_note:',cmd)
        import subprocess
        subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        print('note over')

    def _for_cgtw(self):
        database = self.current_project_data['database']
        eps = self.eps_comb.currentText()
        module = 'asset' if eps == 'Asset' else 'shot'
        note = self.note_text.toPlainText()
        task_name = self.task_name_comb.currentText()
        cg_id = self.task_data[task_name]['cg_id'] if eps != 'Asset' else self.current_asset['cg_id']
        task_id = cg_id.split(',')[2]  # if eps != 'Asset' else ''
        mov = self.mov_comb.currentText()
        self.cmd_cgtw_note(database, module, task_id, note)
        self.cmd_cgtw_submit(database, module, task_id, mov, note)

    def timerEvent(self, tevent):

        percent = self.count * 100 / (self.all_count + 0.001)
        self.progress.set_percent(percent)
        # temp_list = []
        # err_list = []
        # for i in self.all_path_list:
        #     if os.path.exists(i[1]):
        #         temp_list.append(i[1])
        #     else:
        #         err_list.append(i[0])
        # self.discopys = err_list
        # if percent > 99:
        #     if len(temp_list) == self.all_count:
        #         print(u'pack over')
        #         self.progress.close()
        #         self.timer.stop()
        #         self._for_cgtw()
        #     else:
        #         print('file_cout:',self.file_cout)
        #         print('all_count:',self.all_count)

        if percent > 99.9:
            self.progress.close()
            self.timer.stop()
            self._for_cgtw()
            print('stop do')
            discopys = []
            for i in self.all_path_list:
                if not os.path.exists(i[1]):
                    discopys.append(i[0])
            if discopys:
                QMessageBox.information(None,u'未提交文件','\n'.join(self.discopys))

    def closeEvent(self, *args, **kwargs):
        self.setHidden(True)


def maya_ui():
    try:
        dialog.show()
        dialog.setHidden(False)
    except:

        dialog = GlobalControl(parent=maya_main_window())
        dialog.show()


# 实例化窗口
if __name__ == "__main__":
    maya_ui()
    '''
    try:
        ui.deleteLater()
    except:
        pass
    ui = GlobalControl()

    try:
        ui.create()
        ui.show()
    except:
        ui.deleteLater()
        '''
